Grammar:
exec() : RegExpObject.exec(string) match() : stringObject.match(string) stringObject.match(regexp)
Knowledge points:
exec() is a method of RegExp object, and match() is a method of String object.
will return an array containing information about the first match; or null if there is no match.
The returned array, although an instance of Array, contains two additional properties: index and input. Among them, index represents the position of the match in the string, and input represents the string to which the regular expression is applied.
In the array, the first item is the string that matches the entire pattern, and the other items are strings that match the capturing groups in the pattern (if there are no capturing groups in the pattern, the array contains only one item).
Test:
Test code for match():
var text = "mom and dad and baby"; var pattern = /(mom and )?(dad and )?baby/; var matches = text.match(pattern);//pattern.exec(text); console.log(matches.index); console.log(matches.input); console.log(matches[0]); console.log(matches[1]); console.log(matches[2]);
Screenshot of test results for match():
Test code for exec():
var text = "mom and dad and baby"; var pattern = /(mom and )?(dad and )?baby/; var matches = pattern.exec(text);//text.match(pattern); console.log(matches.index); console.log(matches.input); console.log(matches[0]); console.log(matches[1]); console.log(matches[2]);
Screenshot of test results for exec():
String object method
方法 | 描述 |
exec | 检索字符串中指定的值。返回找到的值,并确定其位置 |
test | 检索字符串中指定的值。返回 true 或 false。 |
String object method
方法
描述
match()
找到一个或多个正则表达式的匹配。
replace()
替换与正则表达式匹配的子串。
search()
检索与正则表达式相匹配的值。
This is the introduction to the test of return values and attributes of match() and exec() in JS. I hope it will be helpful to you!