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 it:
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
};
}
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 or there a better cross browser method of doing this?
FIDDLE: http://jsfiddle.net/trex005/324k2as5/.
You simplify it to
new RegExp(regex.source, regex.flags);
Note RegExp.prototype.flags is introduced in ES6, so you may need to polyfill it:
if (RegExp.prototype.flags === undefined) {
Object.defineProperty(RegExp.prototype, 'flags', {
configurable: true,
get: function() {
return this.toString().match(/[gimuy]*$/)[0];
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With