multiple replaces with javascript [duplicate]
In PHP, you do this to replace more then one value at a time.
<?php
$string = "i am the foobar";
$newstring = str_replace(array('i', 'the'), array('you', 'a'), $string);
echo $newstring;
?>
How do you do this in javascript?
Use javascript's .replace()
method, stringing multiple replace's together. ie:
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"
You could do:
http://jsfiddle.net/ugKRr/
var string = "jak har en mamma";
string = string.replace(/(jak)|(mamma)/g,function(str,p1,p2) {
if(p1) return 'du';
if(p2) return 'pappa';
});
or:
http://jsfiddle.net/ugKRr/2/
var string = "jak har en mamma";
string = string.replace(/jak/g,'du').replace(/mamma/g,'pappa');
精彩评论