使用exec()方法可以返回匹配到的字符串。该方法在匹配成功时返回一个数组,包含匹配到的字符串及其它信息,如果匹配失败,则返回null。数组的第一个元素是匹配到的字符串,后面的元素是分组捕获的字符串(如果有的话)。例如:

var str = "Hello, World!";
var pattern = /Hello/;
var result = pattern.exec(str);
console.log(result); // ["Hello"]

如果正则表达式中有分组捕获,则可以通过数组的索引访问到对应的字符串。例如:

var str = "John Smith (age 30)";
var pattern = /(\w+)\s+(\w+)\s+\(age (\d+)\)/;
var result = pattern.exec(str);
console.log(result); // ["John Smith (age 30)", "John", "Smith", "30"]
console.log(result[1]); // "John"
console.log(result[2]); // "Smith"
console.log(result[3]); // "30"
js正则如何返回匹配到的字符串

原文地址: https://www.cveoy.top/t/topic/buIu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录