查找并替换超过1个单词?

我需要使用jQuery在页面上更改一堆不同的单词。 这是我到目前为止的代码:

(function($) { var thePage = $("body"); thePage.html(thePage.html().replace([/My Classes/g, 'My Levels'],)); })(jQuery) 

如何修改此代码以便查找和替换更多单词? 让我们说我也想用“猫”代替“狗”,用“女孩”代替“男孩”。

您可以做的是链接替换值,例如:

 thePage.html(thePage.html().replace([/My Classes/g, 'My Levels'],)) .replace([/dog/g, 'cat'],)) .replace([/bird/g, 'pen'],)); 

编辑:

这是您在jsfiddle上提供的更新代码

 (function($) { $(function(){ var thePage = $("body"); thePage.html(thePage.html().replace(/My Classes/g, 'My Levels').replace(/dog/g, 'cat').replace(/bird/g, 'pen')); }); })(jQuery)​ 

和jsfiddle链接:

http://jsfiddle.net/BEftd/4/

从这里尝试这个优雅的解决方案

 for (var val in array) text= text.split(val).join(array[val]); 

您可以定义表示搜索和替换术语的键值对数组,然后像这样循环遍历它。 不需要jQuery!

你决不需要jQuery这样做,但是在不知道你在做什么的情况下很难给出一个好的答案。 例如,“dog”和“boy”可以出现在单词中。 你想要替换那些实例,还是仅仅用完整的单词? 如果它们属于属性 – 或者它们本身是属性或元素,该怎么办? 有某种优先权吗?

也就是说,JavaScript String没有方法可以一次替换多个单词。 你可以链接.replace ,或者你可以实现类似的东西:

 String.prototype.replaceMulti = function (args) { for (var x = 0; x < args.length; x++) { this = this.replace(args.from, args.to); } } thePage.html(thePage.html().replaceMulti([{from: /dog/g, to: 'cat'}]);