Replace Multiple String at Once With Regex in Javascript

前端 未结 3 1935
走了就别回头了
走了就别回头了 2020-12-11 04:48

I tried this : Replace multiple strings at once And this : javascript replace globally with array how ever they are not working.

Can I do similar to this (its PHP):<

3条回答
  •  死守一世寂寞
    2020-12-11 05:42

    var str = "I have a cat, a dog, and a goat.";
    var mapObj = {
       cat:"dog",
       dog:"goat",
       goat:"cat"
    };
    str = str.replace(/cat|dog|goat/gi, function(matched){
      return mapObj[matched];
    });
    

    Check fiddle

提交回复
热议问题