在Javascript中,matchAll()方法用于针对regex(正则表达式)返回与参考字符串匹配的所有迭代器。 matchAll()方法的一个重要用途是它可以用于捕获带有/g标志的组,这使其比match()方法具有优势,后者忽略了带有/g标志的捕获组。
用法:
str.matchAll(Regexp)
- str:这是要找到匹配项的参考字符串。
- Regexp:它只是一个正则表达式对象。 RegExp对象必须包含/g标志,否则将引发TypeError。
- 返回值:它是一个迭代器。
例:
HTML
<html>
<body>
<script>
function myFunction() {
//Regular expression with the /g flag
const regex = /e(xam)(ple(\d?))/g;
//Reference string
const str = 'example1example2example3';
//Using matchAll() method
const array = [...str.matchAll(regex)];
console.log(array[0]);
console.log(array[1]);
console.log(array[2]);
}
myFunction();
</script>
</body>
</html>
输出:
在上面的示例中,我们能够使用matchAll()方法找到匹配项并捕获内部组。
相关用法
- JavaScript Symbol.matchAll属性用法及代码示例
- Javascript String startsWith()用法及代码示例
- Javascript String toUpperCase()用法及代码示例
- Javascript String toLowerCase()用法及代码示例
- Javascript String split()用法及代码示例
- JavaScript String endsWith()用法及代码示例
- Javascript String concat()用法及代码示例
- Javascript String trim()用法及代码示例
- Javascript String substr()用法及代码示例
- Javascript String includes()用法及代码示例
- Javascript string.toString()用法及代码示例
- Javascript string.codePointAt()用法及代码示例
- Javascript String.fromCodePoint()用法及代码示例
- Javascript string.localeCompare()用法及代码示例
- Javascript string.valueOf()用法及代码示例
- Javascript string.slice()用法及代码示例
- Javascript string.normalize()用法及代码示例
- Javascript string.search()用法及代码示例
注:本文由纯净天空筛选整理自ashutoshrathi大神的英文原创作品 Javascript String matchAll() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。