javascript 正则表达式 - 新的 RegExp() 全局搜索/替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7313928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:43:03  来源:igfitidea点击:

Regular Expression - new RegExp() searching/replacing string globally

javascriptregexreplaceclassname

提问by magenta placenta

I'm working on a project which at the moment is unable to have any 3rd party JS libraries (otherwise this would be a breeze with jQuery). One of the things within this project is form validation. I've got that working fairly well except for some minor issues with my regex.

我正在开发一个项目,该项目目前无法拥有任何 3rd 方 JS 库(否则这对 jQuery 来说将是轻而易举的)。该项目中的一件事是表单验证。除了我的正则表达式的一些小问题外,我已经很好地工作了。

I'm triggering a validation function onchange() of text fields so if you tab out and there's an error you'll know immediately. Tab out with good data and you'll know immediately as well. If the validation fails, I assign an errorclass to a parent element. This works fine if you only trip the validation once. If you keep failing the test, the error classes build up, for example, if you fail the validation 2x, you'll end up with:

我正在触发文本字段的 onchange() 验证功能,因此如果您退出并出现错误,您会立即知道。选择好的数据,您也会立即知道。如果验证失败,我会为父元素分配一个错误类。如果您只进行一次验证,这可以正常工作。如果您一直未能通过测试,错误类就会累积起来,例如,如果您的验证失败 2 次,您最终会得到:

<p class=" error">

If you fail 3x, you'll end up with:

如果你失败了 3 次,你最终会得到:

<p class=" error error">

If the validation passes, I call the removeClass() function below. Basically, it doesn't look like I'm getting a global search/replace. I thought for sure that adding the global modifier would take care of the case above, but it does not, it only removes one "error" class.

如果验证通过,我会调用下面的 removeClass() 函数。基本上,我似乎没有进行全局搜索/替换。我确信添加全局修饰符会处理上述情况,但事实并非如此,它只会删除一个“错误”类。

removeClass: function (el, name) {
    var regex = new RegExp('(^|\s)' + name + '(\s|$)', 'gi');
    el.className = el.className.replace(regex, ' ');
}

My regex is just looking for beginning of line or white space followed by "error" followed by white space or end of line. Granted, I admittedly suck at regular expressions :)

我的正则表达式只是在寻找行首或空格,然后是“错误”,然后是空格或行尾。当然,我承认我很擅长正则表达式 :)

Anything jump out at you?

有什么东西向你扑来?

回答by user113716

It is working globally, but when a match is found, the next attempted match begins in the character following the last character in the previous match, which is the ein the second errorinstead of the space before it.

这是全球范围内的工作,但是当找到一个匹配,下一试图匹配的字符在之前的比赛,这是最后一个字符开始e在第二error,而不是空间之前它。

//  v-----v-------first match
   " error error"
//         ^------continues here, no more matches because 
//                       there isn't a space before `e`.

To test it, add a second space between the two classes, and it will work.

要测试它,在两个类之间添加第二个空格,它将起作用。

//  v-----v-------first match
   " error  error"
//         ^------continues here, and now it will match 

A fix would be to use \\binstead, which doesn't match any character, so the next match will start after the last rcharacter in the previous errormatch.

解决方法是\\b改用它,它不匹配任何字符,因此下一个匹配将在上一个匹配中的最后一个r字符之后开始error

new RegExp('\b' + name + '\b', 'gi');


As noted by @Joseph, you should change the " "in the .replace()to an empty string ""in order to avoid an accumulation of space characters.

正如@Joseph所指出的,您应该将" "in更改为.replace()空字符串"",以避免空格字符的积累。