What's wrong with .match () javascript

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

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

Why is .match () not recommended?

+4
source share
3 answers

The main advantage of exec is that it returns capture groups. For instance:

 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] 

Review the coding standards that you have published; the document contains many seemingly arbitrary recommendations. Obviously, it aims to achieve greater consistency, so it is possible that exec is preferred because it has more functionality - it needs to be used in some cases, so they can always use it as well.

In a personal note, I don't care about principles without explanation, so this is a good thing you asked for. In many cases, this leads to dogmatic or superstitious programming.

+1
source

Consider:

Given:

 var Str = 'Here are some words.'; var myRegex = /(\w+)/ig; 

.

In 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 easier exec() ?
(I, too.)

Both functions are fully supported according to my diagram (except that the match() results also have an input member in IE).

I could not find excuses for solving people in jQuery.

+3
source

This is the style.

The big difference is that match is called like this:

 string.match(regex) 

So far, test and exec are called like this:

 regex.exec(string) 
+1
source

Source: https://habr.com/ru/post/1314391/


All Articles