开发者

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

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.

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 error 开发者_运维知识库class 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:

<p class=" error">

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

<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: 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?


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 e in the second error instead of the space before it.

//  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 \\b instead, which doesn't match any character, so the next match will start after the last r character in the previous error match.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜