查找并替换多个单词 JavaScript

Find and replace multiple words JavaScript

本文关键字:单词 JavaScript 替换 查找      更新时间:2023-09-26

我想用JavaScript替换一个单词,我的代码如下:

$('#test').contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace('microsoft', 'Hi I am
replace'),('bob', 'bobart')    
});

该代码适用于第一个实例,将替换Microsoft但不会更改 Bob,我如何添加多个单词以替换到其中?

谢谢

使用 .replace('x','y').replace('a','b') 使用替换链接:

his.textContent.replace('microsoft', 'Hi I am replace').replace('bob', 'bobart')   
你可以

这样做:

var replacers = {"to_be_replaced_1": "by_this_1","to_be_replaced_2":"by_this_2"},
    stringToBeReplaced = "some text to_be_replaced_1";
$.each(replacers ,function(replaceable, replacer){
   stringToBeReplaced.replace(replaceable, replacer);
});