You know the problem with regular expressions in JavaScript?: There’s not enough to do. Sure, you can use its methods against strings but there’s nothing that allows you to manipulate the actual expressions. Where is the property for all the modifiers? How can you add or remove a modifier? The simple answer is that it isn’t possible. The long and complicated way says that it is. The only problem is that the code is a little bit ugly:
RegExp.prototype.modifiers = function() {
return /^\/(.+)\/([gim]+?)$/i.exec(this.toString())[2].split('');
};
Don’t say I didn’t warn you.
In short, that method converts the expression to a string and then executes another regular expression with it. This new regular expression takes away the main pattern and leaves the modifiers in a string. That string is then split into individual characters so you have an array of them (for example: ['g', 'i']).
This magic regular expression can also be used for extracting a pattern, which, in turn, allows you to rebuild it with the RegExp constructor — modifiers included. This is the method for extracting the pattern:
RegExp.prototype.pattern = function() {
return /^\/(.+)\/([gim]+?)$/i.exec(this.toString())[1];
};
Rebuilding it is as simple as this:
var original = /\s+/g;
var pattern = original.pattern();
var modifiers = original.modifiers().join('');
var better = new RegExp(pattern, modifiers);
So, putting two and two together, if we can extract the pattern and the modifiers, and rebuild it, what’s stopping us from changing it along the way? Enter addModifiers and removeModifiers:
RegExp.prototype.addModifiers = function(modifiers) {
return new RegExp(this.pattern(), this.modifiers().join('') + modifiers.join(''));
};
RegExp.prototype.removeModifiers = function(modifiers) {
return new RegExp(this.pattern(), this.modifiers().join('').replace(new RegExp(modifiers.join('|'), 'i'), ''));
};
With the addModifiers method, you may have noticed that I haven’t bothered to check for the existing modifiers. This is because you can duplicate a modifier on a regular expression and it won’t matter as it’ll only be counted once. Both of these methods allow multiple modifiers and require them to be an array (['g', 'i']):
var original = /\s+/g;
original = original.addModifiers(['i']); // /\s+/gi
original = original.removeModifiers(['g']); // /\s+/i
pattern = original.pattern(); // '\s+'
modifiers = original.modifiers(); ['i']
Comments
No responses have been made so far. Add your comments.