jeudi 13 août 2015

Remove global flag from RegExp

Given a user (developer) provided regular expression, I need to remove the global flag if it exists. On firefox 38 and above you can just set it1 :

the_regex.global = false;

However that is not supported elsewhere. So, I have created this pair of functions:

function deGlobal(regex){
    if(!regex instanceof RegExp)return regex;
    if(!regex.global)return regex;
    var parts = regExpParts(regex);
    console.log(parts);
    if(parts){
        return new RegExp(parts.pattern,parts.flags.replace("g",""));
    } else {
        return false;
    }
}
function regExpParts(regex){
    if(!regex instanceof RegExp)return false;
    var regex_string = regex.toString();
    var flags = regex_string.substring(regex_string.lastIndexOf('/')+1);
    var pattern = regex_string.substring(1,regex_string.lastIndexOf('/'));
    return {flags:flags,pattern:pattern};
}

fiddle: http://ift.tt/1Par3As

Which for all of my test cases is doing great, but it seems like a very error prone method. Is there a case where these functions wouldn't work? Is there a better cross browser method of doing this?

1 http://ift.tt/1TxneMc



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire