js match函数注意


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"];
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM