string JS使用变量替换所有出现的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17820039/
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-09-09 02:01:41  来源:igfitidea点击:

JS replacing all occurrences of string using variable

javascriptstringvariablesreplace

提问by usama8800

I know that str.replace(/x/g, "y")replaces all x's in the string but I want to do this

我知道这会str.replace(/x/g, "y")替换字符串中的所有 x,但我想这样做

function name(str,replaceWhat,replaceTo){
    str.replace(/replaceWhat/g,replaceTo);
}

How can i use a variable in the first argument?

如何在第一个参数中使用变量?

回答by Barmar

The RegExpconstructor takes a string and creates a regular expression out of it.

RegExp构造函数接受一个字符串,并创建一个正则表达式出来。

function name(str,replaceWhat,replaceTo){
    var re = new RegExp(replaceWhat, 'g');
    return str.replace(re,replaceTo);
}

If replaceWhatmight contain characters that are special in regular expressions, you can do:

如果replaceWhat可能包含正则表达式中的特殊字符,您可以执行以下操作:

function name(str,replaceWhat,replaceTo){
    replaceWhat = replaceWhat.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&');
    var re = new RegExp(replaceWhat, 'g');
    return str.replace(re,replaceTo);
}

See Is there a RegExp.escape function in Javascript?

请参阅JavaScript 中是否有 RegExp.escape 函数?

回答by Hogan

The third parameter of flags below was removed from browsers a few years ago and this answer is no longer needed -- now replace works global without flags

几年前从浏览器中删除了下面标志的第三个参数,不再需要这个答案——现在替换没有标志的全局工作



Replace has an alternate form that takes 3 parameters and accepts a string:

Replace 有另一种形式,它接受 3 个参数并接受一个字符串:

function name(str,replaceWhat,replaceTo){
    str.replace(replaceWhat,replaceTo,"g");
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace