dh-dh

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

分类:

技术点:

相关文章: