简体   繁体   中英

How can I call a function from regular expression matches in javascript

I have a regular expression and I'm wondering if I can use all matches as an argument for a function. For example, let's say that I have a data set

Hello heelo hhhheEEeloo eelloooo

and a regular expression

/[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/

which would match

Hello heelo hhhheEEeloo

how can I get a javascript function to take in each match as an argument, for example

function isHello(arg) {
    if (arg == 'Hello') { return 1 }
    else { return 0}
}

Use .replace with a callback

"Hello heelo hhhheEEeloo eelloooo".replace(/[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/g,function(match){
    //Your function code here
    return match;
})

Or a more trivial example:

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

var string = "Hello heelo hhhheEEeloo eelloooo",
    regex = /[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/g,
    fn = function(arg){ 
        if (arg == 'Hello')
             return 1;
        return 0
    };
string.match(regex).forEach(fn);

Notice the g flag added to the regex to match in order to give the desired match.

Here is an example using match() :

var s = "Hello heelo hhhheEEeloo eelloooo";

s.match(/[Hh]{1,}[Ee]{1,}[Ll]{1,}[Oo]{1,}/g).forEach(function(entry) {
    // your function code here, the following is just an example
    if (entry === "Hello")
        console.log("Found Hello!");
    else
        console.log(entry + " is not Hello");
    return;
});

Example: http://jsfiddle.net/wTMuF/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM