Replace Multiple String at Once With Regex in Javascript

前端 未结 3 1932
走了就别回头了
走了就别回头了 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:32

    One possible solution:

    var a = ['a','o','e'],
        b = ['1','2','3'];
    
    'stackoverflow'.replace(new RegExp(a.join('|'), 'g'), function(c) {
        return b[a.indexOf(c)];
    });
    

    As per the comment from @Stephen M. Harris, here is another more fool-proof solution:

    'stackoverflow'.replace(new RegExp(a.map(function(x) {
        return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }).join('|'), 'g'), function(c) {
        return b[a.indexOf(c)];
    });
    

    N.B.: Check the browser compatibility for indexOf method and use polyfill if required.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-11 05:45

    You can use delimiters and replace a part of the string

    var obj = {
      'firstname': 'John',
      'lastname': 'Doe'
    }
    
    var text = "My firstname is {firstname} and my lastname is {lastname}"
    
    console.log(mutliStringReplace(obj,text))
    
    function mutliStringReplace(object, string) {
          var val = string
          var entries = Object.entries(object);
          entries.filter((para)=> {
              var find = '{' + para[0] + '}'
              var regExp = new RegExp(find,'g')
           val = val.replace(regExp, para[1])
        })
      return val;
    }

    0 讨论(0)
提交回复
热议问题