正则并不适合严格查找子串

正则表达式带有局限性,适合匹配,不适合查找;
 
原理:正则匹配到子串后,会从子串的结尾处开始继续匹配
 
比如“aaaca ”中查找所有“aa”的子串,按理来说应该有2个“aa”子串(01、12);然而,全局正则匹配到01位后,继续从2位开始匹配,就会忽略到12位的子串,所以只会匹配到1个子串
    var red = /aa/g;
    console.log(red.exec("aaaca"));     // ["aa", index: 0, input: "aaaca"]
    console.log(red.exec("aaaca"));     // null
 
解决方式:乖乖用indexOf()吧,不断改变fromIndex
原文地址:https://www.cnblogs.com/hjqbit/p/7268483.html