Javascript 使用 RegExp 替换字符串模式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6558972/
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
Javascript replacing string pattern using RegExp?
提问by maxcollins
I want to remove any occurances of the string pattern of a number enclosed by square brackets, e.g. [1], [25], [46], [345] (I think up to 3 characters within the brackets should be fine). I want to replace them with an empty string, "", i.e. remove them.
我想删除方括号括起来的数字的字符串模式的任何出现,例如 [1]、[25]、[46]、[345](我认为括号内最多 3 个字符应该没问题)。我想用空字符串“”替换它们,即删除它们。
I know this can be done with regular expressions but I'm quite new to this. Here's what I have which doesn't do anything:
我知道这可以用正则表达式来完成,但我对此很陌生。这是我没有做任何事情的东西:
var test = "this is a test sentence with a reference[12]";
removeCrap(test);
alert(test);
function removeCrap(string) {
var pattern = new RegExp("[...]");
string.replace(pattern, "");
}
}
Could anyone help me out with this? Hope the question is clear. Thanks.
有人可以帮我解决这个问题吗?希望问题很清楚。谢谢。
回答by Felix Kling
[]
has a special meaning in regular expressions, it creates a character class. If you want to match these characters literally, you have to escape them.replace
[docs]only replaces the firstoccurrence of a string/expression, unless you set the global flag/modifier.replace
returnsthe new string, it does not change the string in-place.
[]
在正则表达式中具有特殊意义,它创建了一个字符类。如果你想从字面上匹配这些字符,你必须对它们进行转义。replace
[docs]仅替换字符串/表达式的第一次出现,除非您设置了全局标志/修饰符。replace
返回新字符串,它不会就地更改字符串。
Having this in mind, this should do it:
考虑到这一点,应该这样做:
var test = "this is a test sentence with a reference[12]";
test = test.replace(/\[\d+\]/g, '');
alert(test);
Regular expression explained:
正则表达式解释:
In JavaScript, /.../
is a regex literal. The g
is the global flag.
在 JavaScript 中,/.../
是正则表达式文字。该g
是全局标志。
\[
matches[
literally\d+
matches one or more digits\]
matches]
literally
\[
[
字面上匹配\d+
匹配一位或多位数字\]
]
字面上匹配
To learn more about regular expression, have a look at the MDN documentationand at http://www.regular-expressions.info/.
要了解有关正则表达式的更多信息,请查看MDN 文档和http://www.regular-expressions.info/。
回答by Alnitak
This will do it:
这将做到:
test = test.replace(/\[\d+\]/g, '');
\[
because[
on its own introduces a character range\d+
- any number of digits\]
as above/g
- do it for every occurrence
\[
因为[
它本身引入了一个字符范围\d+
- 任意数量的数字\]
如上/g
- 每次出现都这样做
NB: you have to reassign the result (either to a new variable, or back to itself) because String.replace
doesn't change the original string.
注意:您必须重新分配结果(要么分配给新变量,要么返回给自身),因为String.replace
不会更改原始字符串。