jQuery如果div包含此文本,则替换该部分文本

Dan*_*iel 75 jquery text replace contains

就像标题所说,我想替换div中文本的特定部分.

结构如下所示:

<div class="text_div">
    This div contains some text.
</div>
Run Code Online (Sandbox Code Playgroud)

例如,我想用"hello everyone"替换"contains".我无法找到解决方案.

Jam*_*ice 135

您可以使用该text方法并传递一个返回已修改文本的函数,使用本机String.prototype.replace方法执行替换:

?$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});?????
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子.

  • 你可以使用正则表达式/ iwantreplacethis/g来表示所有的ocurences (2认同)
  • @AaronMatthews这个答案是很久以前的,但我相信这是因为jQuery`text`方法在传递函数时会将选择的文本设置为该函数的返回值.没有`return`,文本将被替换为空. (2认同)

hfa*_*azm 10

非常简单,只需使用此代码,它将保留 HTML,同时仅删除未包装的文本:

jQuery(function($){

    // Replace 'td' with your html tag
    $("td").html(function() { 

    // Replace 'ok' with string you want to change, you can delete 'hello everyone' to remove the text
          return $(this).html().replace("ok", "hello everyone");  

    });
});
Run Code Online (Sandbox Code Playgroud)

这是完整示例:https : //blog.hfarazm.com/remove-unwrapped-text-jquery/


fca*_*ran 8

var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));
Run Code Online (Sandbox Code Playgroud)


grc*_*grc 8

如果可能,您可以在span标记中包含要替换的单词,如下所示:

<div class="text_div">
    This div <span>contains</span> some text.
</div>
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用jQuery轻松更改其内容:

$('.text_div > span').text('hello everyone');
Run Code Online (Sandbox Code Playgroud)

如果无法将其包装在span标记中,则可以使用正则表达式.