what's wrong with .match() javascript
jquery says: http://docs.jquery.com/JQuery_Core_Sty开发者_Go百科le_Guidelines#RegExp
All RegExp operations should be done using .test() and .exec(). "string".match() is no longer used.
Why is .match() not recommended?
Consider:
Given:
var Str = 'Here are some words.';
var myRegex = /(\w+)/ig;
.
With match():
var aWordList = Str.match (myRegex);
var iLen = aWordList.length;
for (var K=0; K < iLen; K++)
{
console.log ('Word: ', K, ' --> ', aWordList[K]);
}
.
With exec():
var aWordList;
var K = 0;
RegExp.lastindex = 0; //-- If this is omitted, nasty side-effects may occur.
while ( (aWordList = myRegex.exec (Str)) != null)
{
console.log ('Word: ', K++, ' --> ', aWordList[0]);
}
.
See how much simpler exec()
is?
(Me neither.)
Both functions are fully supported according to my chart (except that match()
results also have the input
member on IE).
I couldn't find a justification for the decision by the folks at jQuery.
A major benefit of exec
is that it returns capturing groups. For example:
var s = "123456789"
var regex = /.(.)(..)/g;
match:
s.match(regex);
> [1234, 5678]
exec:
regex.exec(s);
> [1234, 2, 34]
regex.exec(s);
> [5678, 6, 78]
Reviewing the coding standards you've posted; the document contains many seemingly arbitrary guidelines. Obviously, it aims to achieve mostly consistency, so it is possible exec
is preferred because it has more functionality - it has to be used on some occasions, so they might as well use it always.
On a personal note, I don't care much for guidelines without explanations, so it's a good thing you've asked. In many cases it leads to dogmatic or superstition-based programming.
This is a style thing.
The big difference is that match
is called like so:
string.match(regex)
While test
and exec
are called like so:
regex.exec(string)
精彩评论