开发者

multiple replaces with javascript [duplicate]

This question already has answers here: Replace multiple strings with multiple other strings (27 answers) Closed 6 years ago. 开发者_JAVA技巧

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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜