用多个其他stringreplace多个string
我试图用多个其他单词replacestring中的多个单词。 string是“我有一只猫,一只狗和一只山羊”。
然而,这并不产生“我有一只狗,一只山羊和一只猫”,而是产生了“我有一只猫,一只猫,一只猫”。 是否有可能在JavaScript中同时用多个其他stringreplace多个string,以便产生正确的结果?
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".
具体解决scheme
你可以使用一个函数来replace每一个。
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]; });
jsfiddle的例子
推广它
如果你想dynamic地维护正则expression式,只需要将未来交换添加到地图上,就可以做到这一点
new RegExp(Object.keys(mapObj).join("|"),"gi");
生成正则expression式。 那么它会看起来像这样
var mapObj = {cat:"dog",dog:"goat",goat:"cat"}; var re = new RegExp(Object.keys(mapObj).join("|"),"gi"); str = str.replace(re, function(matched){ return mapObj[matched]; });
而要添加或更改更多的replace,您可以编辑地图。
摆弄dynamic正则expression式
使其可重用
如果你想这是一个普遍的模式,你可以把这个出来这样的function
function replaceAll(str,mapObj){ var re = new RegExp(Object.keys(mapObj).join("|"),"gi"); return str.replace(re, function(matched){ return mapObj[matched.toLowerCase()]; }); }
那么你可以通过str和你想要的函数replace的地图,它会返回转换后的string。
摆弄function
为了确保Object.keys在旧浏览器中工作,添加一个polyfill(例如从MDN或Es5) 。
在这种情况下,这可能不符合您的确切需求,但是我发现这是一种替代string中多个参数的有用方法,作为一个通用的解决scheme。 它会replace参数的所有实例,无论它们被引用了多less次:
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.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); }; function replaceAll(str, map){ for(key in map){ str = str.replaceAll(key, map[key]); } return str; } //testing... var str = "bat, ball, cat"; var map = { 'bat' : 'foo', 'ball' : 'boo', 'cat' : 'bar' }; var new = replaceAll(str, map); //result: "foo, boo, bar"
用户常规函数定义要replace的模式,然后使用replace函数对inputstring进行处理,
var i = new RegExp('"{','g'), j = new RegExp('}"','g'), k = data.replace(i,'{').replace(j,'}');
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; }
/ *replacestring所需的一些方法,作为我们想要的许多参数,并用我们指定的最后一个参数replace所有的参数2013 CopyRights保存为:最大艾哈迈德这是一个例子:
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/
我在@BenMcCormicks上扩展了一下。 他工作的规则string,但不是如果我逃脱了字符或通配符。 这是我做的
str = "[curl] 6: blah blah 234433 blah blah"; mapObj = {'\\[curl]':'','\\d:',''}; replaceAll: function (str, mapObj) { var arr = Object.keys(mapObj), re; $.each(arr, function (key, value) { re = new RegExp(value, "g"); str = str.replace(re, function (matched) { return mapObj[value]; }); }); return str; }
返回“等等等等234433等等等等”
这样它将匹配mapObj中的键而不是匹配的单词“
<!DOCTYPE html> <html> <body> <p id="demo">Mr Blue has a blue house and a blue car.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var str = document.getElementById("demo").innerHTML; var res = str.replace(/\n| |car/gi, function myFunction(x){ if(x=='\n'){return x='<br>';} if(x==' '){return x=' ';} if(x=='car'){return x='BMW'} else{return x;}//must need }); document.getElementById("demo").innerHTML = res; } </script> </body> </html>
以防万一有人想知道为什么原始海报的解决scheme不起作用:
var str = "I have a cat, a dog, and a goat."; str = str.replace(/cat/gi, "dog"); // now str = "I have a dog, a dog, and a goat." str = str.replace(/dog/gi, "goat"); // now str = "I have a goat, a goat, and a goat." str = str.replace(/goat/gi, "cat"); // now str = "I have a cat, a cat, and a cat."
我写了这个npm包的stringinject https://www.npmjs.com/package/stringinject它允许你做以下;
var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
这将用数组项replace{0}和{1},并返回以下string
"this is a test string for stringInject"
或者你可以用对象键和值replace占位符,如下所示:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" }); "My username is tjcafferkey on Github"