Replace multiple strings with multiple other strings

前端 未结 18 2441
别那么骄傲
别那么骄傲 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:09

    by using prototype function we can replace easily by passing object with keys and values and replacable text

    String.prototype.replaceAll=function(obj,keydata='key'){
     const keys=keydata.split('key');
     return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)
    }
    
    const data='hids dv sdc sd ${yathin} ${ok}'
    console.log(data.replaceAll({yathin:12,ok:'hi'},'${key}'))

提交回复
热议问题