html - Javascript replacing string pattern using RegExp? -
i want remove occurances of string pattern of number enclosed square brackets, e.g. [1], [25], [46], [345] (i think 3 characters within brackets should fine). want replace them empty string, "", i.e. remove them.
i know can done regular expressions i'm quite new this. here's have doesn't anything:
var test = "this test sentence reference[12]"; removecrap(test); alert(test); function removecrap(string) { var pattern = new regexp("[...]"); string.replace(pattern, "");
}
could me out this? hope question clear. thanks.
[]
has special meaning in regular expressions, creates character class. if want match these characters literally, have escape them.replace
[docs] replaces first occurrence of string/expression, unless set global flag/modifier.replace
returns new string, not change string in-place.
having in mind, should it:
var test = "this test sentence reference[12]"; test = test.replace(/\[\d+\]/g, ''); alert(test);
regular expression explained:
in javascript, /.../
regex literal. g
global flag.
\[
matches[
literally\d+
matches 1 or more digits\]
matches]
literally
to learn more regular expression, have @ mdn documentation , @ http://www.regular-expressions.info/.
Comments
Post a Comment