我有一个正则表达式,我想知道是否可以使用所有匹配项作为函数的参数。例如,假设我有一个数据集
Hello heelo hhhheEEeloo eelloooo
和正则表达式
/[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/
匹配
Hello heelo hhhheEEeloo
例如,我怎样才能获得一个 javascript 函数来将每个匹配作为参数?
function isHello(arg) {
if (arg == 'Hello') { return 1 }
else { return 0}
}
最佳答案
使用.replace
带回调
"Hello heelo hhhheEEeloo eelloooo".replace(/[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/g,function(match){
//Your function code here
return match;
})
或者一个更简单的例子:
var count=0;
"aaaaaaa".replace(/a/g,function(match){
console.log("I matched another 'a'",count++);
// just to not replace anything, technically this doesn't matter
//since it doesn't operate on the actual string
return match;
});
Fiddle
关于javascript - 如何从 javascript 中的正则表达式匹配调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326102/