正则表达式替换('/ color [1-9]?[0-9] / g','')在JavaScript中不起作用 [英] Regex replace('/color[1-9]?[0-9]/g','') not working in JavaScript
问题描述
我需要从JavaScript中的字符串中删除所有出现的color1 ... color99。
我为此写了一个简单的正则表达式,但由于某种原因它不起作用:
I need to remove all occurrences of color1...color99 from a string in JavaScript. I wrote a simple regex for this, but it doesn't work for some reason:
> 'color12'.replace('/color[1-9]?[0-9]/g','')
'color12'
但是,如果我创建RegExp对象,它可以工作:
However if I create RegExp object, it works:
> var regex=new RegExp('color[1-9]?[0-9]','g');
> 'color12'.replace(regex,'');
''
我缺少JavaScript regexp语法的哪一部分?
What part of JavaScript regexp syntax am I missing?
推荐答案
根据文档,替换函数输入正则表达式对象或子字符串,替换string 。
According to the Documentation, the replace function takes input an Regex Object or a substring , and an replacement string.
replace()方法返回一个新的字符串,其中
a模式的部分或全部匹配被替换为一个替代品。模式可以是字符串或
RegExp,替换可以是字符串或每个匹配称为
的函数。语法
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. Syntax
str.replace(regexp | substr,newSubStr | function [,flags]);
str.replace(regexp|substr, newSubStr|function[, flags]);
返回
一个新的字符串,其中一些或所有匹配的模式由
替换替换。参数
A new string with some or all matches of a pattern replaced by a replacement. Parameters
regexp
一个RegExp对象。匹配由参数#2的返回值替换。
regexp A RegExp object. The match is replaced by the return value of parameter #2.
substr
将被newSubStr替换的字符串。
substr A String that is to be replaced by newSubStr.
newSubStr
替换从参数#1接收的子字符串的String。支持许多特殊的替换模式;请参阅下面的
将字符串指定为参数部分。
newSubStr The String that replaces the substring received from parameter #1. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.
在您的情况下,它将第一个参数作为子串。由于'color12'没有子串,例如'/ color [1-9]?[0-9] / g',因此不会被替换。
In your case, it takes the first argument as a substring. Since 'color12' does not have a substring such as '/color[1-9]?[0-9]/g', it doesn't get replaced.
如果你改成它,
'color12'.replace(/color[1-9]?[0-9]/g,'')
第一个表达式现在被视为一个RegEx对象,函数返回适当的结果。
The first expression now is treated as a RegEx Object and the function returns the appropriate result.
了解更多:
这篇关于正则表达式替换('/ color [1-9]?[0-9] / g','')在JavaScript中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!