Javascript replacing string pattern using RegExp?
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开发者_StackOverflow中文版 = "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/.
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
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.
精彩评论