我试图用多个其他单词替换字符串中的多个单词。字符串是“我有一只猫,一只狗和一只山羊。”
然而,这并不会产生“我有一只狗、一只山羊和一只猫”,而是产生“我有一只猫、一只猫和一只猫”。是否有可能在JavaScript中同时用多个其他字符串替换多个字符串,以便产生正确的结果?
var str = "I have a cat, a dog, and a goat.";
str = str.replace(/cat/gi, "dog");
str = str.replace(/dog/gi, "goat");
str = str.replace(/goat/gi, "cat");
//this produces "I have a cat, a cat, and a cat"
//but I wanted to produce the string "I have a dog, a goat, and a cat".
在这个实例中,这可能不能满足您的确切需求,但我发现这是一种有用的方法,可以替换字符串中的多个参数,作为通用解决方案。它将替换参数的所有实例,无论它们被引用了多少次:
String.prototype.fmt = function (hash) {
var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
}
你可以这样调用它:
var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
// person = 'Agent Jack Bauer'
String.prototype.replaceSome = function() {
var replaceWith = Array.prototype.pop.apply(arguments),
i = 0,
r = this,
l = arguments.length;
for (;i<l;i++) {
r = r.replace(arguments[i],replaceWith);
}
return r;
}
/*
字符串的replaceSome方法
它需要尽可能多的参数,然后替换所有参数
我们指定的最后一个参数
2013年版权保存:Max Ahmed
这是一个例子:
var string = "[hello i want to 'replace x' with eat]";
var replaced = string.replaceSome("]","[","'replace x' with","");
document.write(string + "<br>" + replaced); // returns hello i want to eat (without brackets)
*/
jsFiddle: http://jsfiddle.net/CPj89/
我写了这个npm包stringinject https://www.npmjs.com/package/stringinject,它允许你做以下事情
var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
这将替换{0}和{1}与数组项,并返回以下字符串
"this is a test string for stringInject"
或者你可以像这样用对象键和值替换占位符:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
"My username is tjcafferkey on Github"