Basic usage of match() for strings

match() is a method of the string type in JavaScript, which can be used to retrieve whether a string contains a specified character or substring. The basic syntax is as follows:

str.match(regexp)

Where regexp can be a regular expression object or a string. If there is no matching result, null is returned.
When regexp is a string, it is implicitly converted to a regular expression object, and only the first matching result is returned. If you need to return all matching results, you need to use the global matching g modifier:

const str = 'hello,world!';
const matches = str.match(/l/g);
console.log(matches);  // 输出["l","l","l"]

In the above example, the string "hello, word!" matches three strings "l", so the marches array contains three elements. It should be noted that using parentheses in regular expressions can define capturing groups, and the values ​​of these captured groups can also be obtained through the match() method. For example:

const str = "holle,world!";
const matches = str.match(/(\w+),(\w+)!/);
console.log(matches);  // 输出["hello,world!","hello","world"]

In the above example, the regular expression /\w+,\w+!/ matches the string "hello,world!" and defines two capturing groups, matching "hello" and "world" respectively. Therefore the matches array contains the entire match result and two non-capturing groups. For more detailed usage of the match() method, it is recommended to refer to the official documentation of MDN: String.prototype.match().

Guess you like

Origin blog.csdn.net/weixin_56733569/article/details/130728199