Replace multiple strings with multiple other strings

前端 未结 18 2024
别那么骄傲
别那么骄傲 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条回答
  •  醉酒成梦
    2020-11-22 05:00

    I expanded on @BenMcCormicks a bit. His worked for regular strings but not if I had escaped characters or wildcards. Here's what I did

    str = "[curl] 6: blah blah 234433 blah blah";
    mapObj = {'\\[curl] *': '', '\\d: *': ''};
    
    
    function replaceAll (str, mapObj) {
    
        var arr = Object.keys(mapObj),
            re;
    
        $.each(arr, function (key, value) {
            re = new RegExp(value, "g");
            str = str.replace(re, function (matched) {
                return mapObj[value];
            });
        });
    
        return str;
    
    }
    replaceAll(str, mapObj)
    

    returns "blah blah 234433 blah blah"

    This way it will match the key in the mapObj and not the matched word'

提交回复
热议问题