Home > Article > Web Front-end > Explanation of the differences between test, exec, and match methods in js regular expressions_javascript skills
Explanation of the differences between test, exec, and match methods in js regular expressions
test
test returns Boolean to find whether the pattern exists in the corresponding string.
var str = "1a1b1c";
var reg = new RegExp("1.", "");
alert(reg.test(str)); // true
exec
exec finds and returns the current matching results as an array.
var str = "1a1b1c";
var reg = new RegExp("1.", "");
var arr = reg.exec(str);
If the pattern does not exist, then arr is null, otherwise arr is always an array of length 1 whose value is the current match. arr also has three attributes: index is the position of the current match; lastIndex is the end position of the current match (index is the length of the current match); input In the above example, input is str.
The exec method is affected by the parameter g. If g is specified, the next time exec is called, the search will start from the last matching lastIndex.
var str = "1a1b1c";
var reg = new RegExp("1.", "");
alert(reg.exec(str)[0]);
alert(reg .exec(str)[0]);
The above two outputs are both 1a. Now look at the specified parameter g:
var str = "1a1b1c";
var reg = new RegExp("1.", "g");
alert(reg.exec(str)[0 ]);
alert(reg.exec(str)[0]);
The first one above outputs 1a, and the second one outputs 1b.
match
match is a method of String object.
var str = "1a1b1c";
var reg = new RegExp("1.", "");
alert(str.match(reg));
match This method is a bit like exec , but: exec is a method of RegExp object; math is a method of String object. Another difference between the two is the interpretation of parameter g.
If parameter g is specified, match returns all results at once.
var str = "1a1b1c";
var reg = new RegExp("1.", "g");
alert(str.match(reg));
//alert(str .match(reg)); // The result of this sentence is the same as the previous sentence
This result is an array with three elements: 1a, 1b, 1c.
Regular expressions are often used in JavaScript, and the two functions Match and Test are often used in regular expressions, and of course Exec. Let’s use code examples to distinguish the differences between them.
Match Example
OUTPUT
---------------------------------
A 1
B 2
C 3
D 4
E 5
a 27
b 28
c 29
d 30
e 31
OUTPUT
---------------------------------
abb 3
ab 9