Javascript myString.replace( VARIABLE, "") ......但全局

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

myString.replace( VARIABLE, "") ...... but globally

javascriptstringvariablesreplace

提问by monkey blot

How can I use a variable to remove all instances of a substring from a string? (to remove, I'm thinking the best way is to replace, with nothing, globally... right?)

如何使用变量从字符串中删除子字符串的所有实例?(要删除,我认为最好的方法是在全球范围内什么都不替换......对吗?)

if I have these 2 strings,

如果我有这两个字符串,

myString = "This sentence is an example sentence."
oldWord = " sentence"

then something like this

然后像这样

myString.replace(oldWord, "");

only replaces the first instance of the variable in the string.

只替换字符串中变量的第一个实例。

but if I add the global g like this myString.replace(/oldWord/g, "");it doesn't work, because it thinks oldWord, in this case, is the substring, not a variable. How can I do this with the variable?

但是如果我像这样添加全局 gmyString.replace(/oldWord/g, "");它不起作用,因为它认为 oldWord 在这种情况下是子字符串,而不是变量。我怎样才能用变量做到这一点?

回答by u283863

Well, you can use this:

嗯,你可以使用这个:

var reg = new RegExp(oldWord, "g");
myString.replace(reg, "");

or simply:

或者干脆:

myString.replace(new RegExp(oldWord, "g"), "");

回答by Erik Reppen

You have to use the constructor rather than the literal syntax when passing variables. Stick with the literal syntax for literal strings to avoid confusing escape syntax.

传递变量时,您必须使用构造函数而不是文字语法。坚持使用文字字符串的文字语法,以避免混淆转义语法。

var oldWordRegEx = new RegExp(oldWord,'g');

myString.replace(oldWordRegEx,"");

回答by GOTO 0

No need to use a regular expression here: split the string around matches of the substring you want to remove, then join the remaining parts together:

此处无需使用正则表达式:围绕要删除的子字符串的匹配项拆分字符串,然后将其余部分连接在一起:

myString.split(oldWord).join('')

In the OP's example:

在 OP 的示例中:

var myString = "This sentence is an example sentence.";
var oldWord = " sentence";
console.log(myString.split(oldWord).join(''));

回答by MatthewS

According to the docs at MDN, you can do this:

根据 MDN 上的文档,您可以这样做:

var re = /apples/gi;
var str = 'Apples are round, and apples are juicy.';
var newstr = str.replace(re, 'oranges');
console.log(newstr);  // oranges are round, and oranges are juicy.

where /gi tells it to do a global replace, ignoring case.

/gi 告诉它进行全局替换,忽略大小写。