首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >jQuery查找和替换字符串

jQuery查找和替换字符串
EN

Stack Overflow用户
提问于 2011-02-25 16:37:11
回答 6查看 436.9K关注 0票数 92

我在网站上的某个地方有一个特定的文本,假设是"lollypops",我想用“marshMellows.”替换所有出现这个字符串的地方。问题是我不知道文本的确切位置。我知道我可以这样做:

代码语言:javascript
复制
$(body).html($(body).html().replace('lollypops', 'marshmellows'));

这可能会起作用,但我需要重写尽可能少的HTML,所以我的想法如下:

即使在attributes中,也要搜索字符串

  1. find
  2. parent element
  3. rewrite this in attributes,但不是全部,例如,在element
  4. replace中替换它,但不在src

中替换它

例如,我会有这样的结构

代码语言:javascript
复制
<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>

在本例中,每次出现"lollypops“都将被替换,只有<img src="...将保持不变,唯一实际被操作的元素将是<a>和两个<span>

有人知道怎么做吗?

EN

回答 6

Stack Overflow用户

发布于 2011-02-25 16:50:50

你可以这样做:

代码语言:javascript
复制
$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

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

此外,这可能存在性能问题。一般来说,jQuery或javascript并不真正适合这种操作。你最好在服务器端这样做。

票数 162
EN

Stack Overflow用户

发布于 2011-02-25 17:20:29

你可以这样做:

代码语言:javascript
复制
$(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'
});

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

票数 15
EN

Stack Overflow用户

发布于 2013-10-14 19:05:57

下面是我用彩色文本替换一些文本的代码。它很简单,只需获取文本并将其替换为HTML标记。它对类标签中的每个单词都有效。

代码语言:javascript
复制
$('.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);
});
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5115152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档