jQuery查找并替换字符串

cyp*_*her 72 javascript jquery jquery-selectors

我在网站上有一个特定的文本,让我们说"lollypops",我想用"marshmellows"替换这个字符串的所有出现.问题是我不知道文本的确切位置.我知道我可以这样做:

$(body).html($(body).html().replace('lollypops', 'marshmellows'));
Run Code Online (Sandbox Code Playgroud)

这可能会有效,但我需要尽可能少地重写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>
Run Code Online (Sandbox Code Playgroud)

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

kgi*_*kis 138

你可以这样做:

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

最好使用需要使用合适的类名检查的文本标记所有标记.

此外,这可能存在性能问题.jQuery或javascript一般不适合这种操作.你最好做服务器端.


ste*_*ecb 14

你可以这样做:

$(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'
});
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/steweb/MhQZD/


Mur*_*ARI 12

你可以这样做:

超文本标记语言

<div class="element">
   <span>Hi, I am Murtaza</span>
</div>
Run Code Online (Sandbox Code Playgroud)


jQuery

$(".element span").text(function(index, text) { 
    return text.replace('am', 'am not'); 
});
Run Code Online (Sandbox Code Playgroud)


Sai*_*hna 8

var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Run Code Online (Sandbox Code Playgroud)


小智 6

下面是我用彩色文本替换一些文本的代码.这很简单,拿出文本并在HTML标签内替换它.它适用于该类标签中的每个单词.

$('.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);
});
Run Code Online (Sandbox Code Playgroud)