Replace multiple strings with multiple other strings

前端 未结 18 2439
别那么骄傲
别那么骄傲 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 04:55

    You can find and replace string using delimiters.

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

提交回复
热议问题