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
JS replacing all occurrences of string using variable
提问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 RegExp
constructor 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 replaceWhat
might 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);
}
回答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