用jQuery替换HTML页面中的文本

时间:2011-02-03 12:46:21

标签: jquery

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

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

7 个答案:

答案 0 :(得分:63)

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

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

如果您想要替换所有出现的单词,则需要使用正则表达式并将其声明为全局/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()查找并更改找到的字符串的第一个匹配项串。或者,如果您想要查找并替换所有出现的字符串,请在混合中引入一些正则表达式。

See a demo here - 查看左上角的HTML以查看原始文本,下面的jQuery以及右下角的输出。

答案 1 :(得分:33)

与此线程中提到的其他人一样,替换整个HTML是一个坏主意,因为它重新插入整个DOM并且可能会破坏任何其他对这些元素起作用的javascript。

相反,请使用jQuery filter

替换页面上的文本,而不是DOM元素本身
  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType是我们要替换其内容的节点类型。 nodeType 3是文本。 See the full list here

答案 2 :(得分:13)

  

...我有一个字符串“-9o0-9909”,我想用另一个字符串替换它。

下面的代码会这样做。

var str = '-9o0-9909';

str = 'new string';

除了笑话之外,用JavaScript替换文本节点并非易事。

我写了一篇关于此事的帖子:Replacing text with JavaScript

答案 3 :(得分:5)

html替换的想法很好,但如果对document.body做了,页面将闪烁,广告将消失。

我的解决方案:
$("*:contains('purrfect')").each(function() { var replaced = $(this).html().replace(/purrfect/g, "purrfect"); $(this).html(replaced); });

答案 4 :(得分:2)

结帐Padolsey's article on DOM find and replace以及the library to implement the described algorithm

在此示例用法中,我将<div id="content">内的所有文本替换为具有tel:方案链接的美国电话号码:

findAndReplaceDOMText(document.getElementById('content'), {
    find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
    replace:function (portion) {
        var a = document.createElement('a');
        a.className = 'telephone';
        a.href = 'tel:' + portion.text.replace(/\D/g, '');
        a.textContent = portion.text;
        return a;
    }
});

答案 5 :(得分:1)

$("#elementID").html("another string");

http://api.jquery.com/html/

答案 6 :(得分:1)

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

表示变量:

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