Replace multiple strings with multiple other strings

前端 未结 18 2383
别那么骄傲
别那么骄傲 2020-11-22 04:14

I\'m trying to replace multiple words in a string with multiple other words. The string is \"I have a cat, a dog, and a goat.\"

However, this does not produce \"I ha

18条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:07

    This worked for me:

    String.prototype.replaceAll = function(search, replacement) {
        var target = this;
        return target.replace(new RegExp(search, 'g'), replacement);
    };
    
    function replaceAll(str, map){
        for(key in map){
            str = str.replaceAll(key, map[key]);
        }
        return str;
    }
    
    //testing...
    var str = "bat, ball, cat";
    var map = {
        'bat' : 'foo',
        'ball' : 'boo',
        'cat' : 'bar'
    };
    var new = replaceAll(str, map);
    //result: "foo, boo, bar"
    

提交回复
热议问题