Javascript使用RegExp替换字符串模式? [英] Javascript replacing string pattern using RegExp?
问题描述
我想删除用方括号括起来的数字字符串模式的任何发生,例如[1],[25],[46],[345](我认为括号内最多3个字符应该没问题)。我想用空字符串替换它们,,即删除它们。
我知道这可以用正则表达式来完成,但我对此很新颖。这是我所拥有的不做任何事情:
var test =这是一个带有参考文献的测试句子[12] ;
removeCrap(test);
alert(test);
函数removeCrap(string){
var pattern = new RegExp([...]);
string.replace(pattern,);
}
任何人都可以帮我解决有了这个?希望问题清楚。谢谢。
-
[]
在正则表达式中有特殊含义,它会创建一个 字符类 。如果你想直接匹配这些字符,你必须将它们转义。
replace
[docs] 只会替换第一个出现的字符串/表达式,除非您设置了全局标志/修饰符。 c>替换 返回新字符串,但不会就地更改字符串。
考虑到这一点,应该这样做:
var test =这是一个参考文献[12]测试句子;
test = test.replace(/ \ [\ d + \] / g,'');
alert(test);
正则表达式解释:
, /.../
是一个正则表达式文字。 g
是全局标志。
-
\ [/ code> [code> [
字面意思] -
\ d +
匹配一个或多个数字 -
\]
匹配]
/ li>
要了解有关正则表达式的更多信息,请查看 MDN文档和 http:// www .regular-expressions.info / 。
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.
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.
[]
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 first occurrence of a string/expression, unless you set the global flag/modifier.replace
returns the new string, it does not change the string in-place.
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.
\[
matches[
literally\d+
matches one or more digits\]
matches]
literally
To learn more about regular expression, have a look at the MDN documentation and at http://www.regular-expressions.info/.
这篇关于Javascript使用RegExp替换字符串模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!