js match函数注意

 2023-09-05 阅读 536 评论 0

摘要:match函数 String.prototype.match 参数 regexp 返回 返回包含所有匹配的数组,如果匹配失败返回Null。数组第一项是整段字符串的匹配,第二项至以后都是捕获匹配。 注意 需要注意的是: If the regular expression includes the g flag, the method return

match函数

String.prototype.match

参数

regexp

返回

返回包含所有匹配的数组,如果匹配失败返回Null。数组第一项是整段字符串的匹配,第二项至以后都是捕获匹配。

注意

需要注意的是:

If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.

如果match函数加了/g标志位,返回的数组里只包含整段字符串的匹配。

比如

`1234567890`.match(/(\d{3})+$/)         //["234567890", "890", index: 1, input: "1234567890"]
`1234567890`.match(/(\d{3})+$/g)       //["234567890"]

解决方案

使用exec函数:

var myRe = /(\d{3})+$/g;
var str = '1234567890';
var myArray;var n = 0;
while ((myArray = myRe.exec(str))&&n<10) {console.log(myArray);n++;        //["234567890", "890", index: 1, input: "1234567890"];
}

转载于:https://www.cnblogs.com/dh-dh/p/7125967.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/562.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息