Replace multiple strings with multiple other strings

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

    This may not meet your exact need in this instance, but I've found this a useful way to replace multiple parameters in strings, as a general solution. It will replace all instances of the parameters, no matter how many times they are referenced:

    String.prototype.fmt = function (hash) {
            var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
    }
    

    You would invoke it as follows:

    var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
    // person = 'Agent Jack Bauer'
    

提交回复
热议问题