简体   繁体   中英

Javascript replacing string pattern using RegExp?

I want to remove any occurances of the string pattern of a number enclosed by square brackets, eg [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, "", ie 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.

  1. [] 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.

  2. replace [docs] only replaces the first occurrence of a string/expression, unless you set the global flag/modifier.

  3. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM