多次替换为 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3293540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:03:58  来源:igfitidea点击:

multiple replaces with javascript

javascriptreplace

提问by Marwelln

In PHP, you do this to replace more then one value at a time.

在 PHP 中,您这样做是为了一次替换多个值。

<?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?

你如何在javascript中做到这一点?

回答by Alex

Use javascript's .replace()method, stringing multiple replace's together. ie:

使用javascript的.replace()方法,将多个替换串在一起。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"

回答by user113716

You could do:

你可以这样做:

http://jsfiddle.net/ugKRr/

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/

http://jsfiddle.net/ugKRr/2/

var string = "jak har en mamma";

string = string.replace(/jak/g,'du').replace(/mamma/g,'pappa');