4

jquery says: http://docs.jquery.com/JQuery_Core_Style_Guidelines#RegExp

All RegExp operations should be done using .test() and .exec(). "string".match() is no longer used.

Why is .match() not recommended?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1. By the way, that would be easier to read (imo) if the titles weren't in comments, but SO titles.
1

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.

2 Comments

"On a personal note, I don't care much for guidelines without explanations" -- Amen, brother. +1
match() returns query-groups, the same, when the /g option is omitted. You just can't cycle through the string like exec() can.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.