简体   繁体   English

Javascript 使用 RegExp 替换字符串模式?

[英]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).我想删除任何出现在方括号内的数字的字符串模式,例如 [1]、[25]、[46]、[345](我认为括号内最多 3 个字符应该没问题)。 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 . []在正则表达式中有特殊含义,它创建一个字符 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. replace [docs]仅替换第一次出现的字符串/表达式,除非您设置全局标志/修饰符。

  3. replace returns the new string, it does not change the string in-place. 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. g是全局标志。

  • \[ matches [ literally \[匹配[字面意思
  • \d+ matches one or more digits \d+匹配一位或多位数字
  • \] matches ] literally \]匹配]字面意思

To learn more about regular expression, have a look at the MDN documentation and at http://www.regular-expressions.info/ .要了解有关正则表达式的更多信息,请查看MDN 文档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 \d+ - 任意位数
  • \] as above \]如上
  • /g - do it for every occurrence /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不会改变原始字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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