在PHP中,您一次只能替换一个值。多个替换为javascript
<?php
$string = "i am the foobar";
$newstring = str_replace(array('i', 'the'), array('you', 'a'), $string);
echo $newstring;
?>
你如何在JavaScript中做到这一点?
在PHP中,您一次只能替换一个值。多个替换为javascript
<?php
$string = "i am the foobar";
$newstring = str_replace(array('i', 'the'), array('you', 'a'), $string);
echo $newstring;
?>
你如何在JavaScript中做到这一点?
使用javascript的.replace()
方法,将多个替换串起来。即:
var somestring = "foo is an awesome foo bar foo foo"; //somestring lowercase
var replaced = somestring.replace(/foo/g, "bar").replace(/is/g, "or");
// replaced now contains: "bar or an awesome bar bar bar bar"
非常好,我正在寻找...我是处理动态字符串,所以我最终看起来像var exp = new RegExp(foo,'g'); somestring.replace(exp,'bar'); – afreeland 2014-12-09 14:13:17
非常好的解决方案。 – 2016-07-15 15:44:18
你可以这样做:
var string = "jak har en mamma";
string = string.replace(/(jak)|(mamma)/g,function(str,p1,p2) {
if(p1) return 'du';
if(p2) return 'pappa';
});
或:
var string = "jak har en mamma";
string = string.replace(/jak/g,'du').replace(/mamma/g,'pappa');
有在#2另一个问题更好的答案。在我看来,最好的答案是[这里](http://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings) – CodeChops 2016-03-29 11:07:38