用jQuery替换HTML页面中的文本 [英] Replace text in HTML page with jQuery

查看:1015
本文介绍了用jQuery替换HTML页面中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何替换jQuery中的任何字符串?

How do I replace any string in jQuery?

假设我有一个字符串"-9o0-9909",我想用另一个字符串替换它.

Let's say I have a string "-9o0-9909" and I want to replace it with another string.

推荐答案

您可以使用以下内容替换页面正文中第一个出现的单词:

You could use the following to replace the first occurrence of a word within the body of the page:

var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);

如果要替换所有出现的单词,则需要使用正则表达式并将其声明为全局/g:

If you wanted to replace all occurrences of a word, you need to use regex and declare it global /g:

var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);

如果您想要一支班轮:

$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));

您基本上是使用<body>标记内的所有HTML都转换为字符串变量. > replace() 查找并使用新字符串更改首次发现的字符串.或者,如果您要查找并替换所有出现的字符串,请在混合中引入一些正则表达式.

You are basically taking all of the HTML within the <body> tags of the page into a string variable, using replace() to find and change the first occurrence of the found string with a new string. Or if you want to find and replace all occurrences of the string introduce a little regex to the mix.

在此处查看演示 -查看左上方的HTML以查看原始内容文字,下面的jQuery和右下角的输出.

See a demo here - look at the HTML top left to see the original text, the jQuery below, and the output to the bottom right.

这篇关于用jQuery替换HTML页面中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆