查找和替换字符串

我在网站上的某个地方有一个特定的文本,让我们说“棒棒糖”,我想替换这个字符串的所有出现“棉花糖”。问题是我不知道文本的确切位置。我知道我可以这样做:

$(body).html($(body).html().replace('lollypops', 'marshmellows'));

这可能会有用,但是我需要尽可能少地重写 HTML,所以我会这样想:

  1. 搜索字符串
  2. 找到最接近的父元素
  3. 只重写最接近的父元素
  4. 甚至在属性中替换它,但不是全部,例如在 class中替换它,但不要在 src中替换它

例如,我会有这样的结构

<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>

在这个例子中,每个出现的“棒棒糖”都将被替换,只有 <img src="...将保持不变,实际操纵的唯一元素将是 <a>和两个 <span>
有人知道怎么做吗?

478872 次浏览

You could do something like this:

$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

You could do something this way:

$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});

example: http://jsfiddle.net/steweb/MhQZD/

Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.

$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});

Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.

HTML:

<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>

jQuery:

$(document).ready(function() {
$('.swapText').text("marshmallows");
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);

You could do something like this:

HTML

<div class="element">
<span>Hi, I am Murtaza</span>
</div>


jQuery

$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});