如果你的系统支持ES9
(意思是如果你的系统支持Ecmascript 2019或更新版本的Chrome、Node.js、Firefox等)
yourString.matchAll( /your-regex/g )
MDN文档
如果您使用NPM
您可以使用官方的polyfill
npm install string.prototype.matchall
const matchAll = require('string.prototype.matchall')
console.log( [... matchAll('blah1 blah2',/blah/g) ] )
否则
这里有一些功能类似的复制粘贴版本
function findAll(regexPattern, sourceString) {
var output = []
var match
var regexPatternWithGlobal = regexPattern.global ? regexPattern : RegExp(regexPattern, regexPattern.flags+"g")
while (match = regexPatternWithGlobal.exec(sourceString)) {
output.push(match)
if (match[0].length == 0) {
regexPatternWithGlobal.lastIndex += 1
}
}
return output
}
function* findAll(regexPattern, sourceString) {
var match
const regexPatternWithGlobal = regexPattern.global ? regexPattern : RegExp(regexPattern, regexPattern.flags+"g")
while (match = regexPatternWithGlobal.exec(sourceString)) {
yield match
if (match[0].length == 0) {
regexPatternWithGlobal.lastIndex += 1
}
}
return output
}
使用示例:
console.log( findAll(/blah/g,'blah1 blah2') )
输出:
[ [ 'blah', index: 0 ], [ 'blah', index: 6 ] ]
str.matchAll(regex)
来迭代获取所有匹配项,包括组的元信息。因此,这个应该是被接受的答案,因为它现在得到了很好的支持。 - undefined