Skip to content

Instantly share code, notes, and snippets.

@tennisonchan
Last active October 25, 2017 16:13
Show Gist options
  • Save tennisonchan/d705a1becf1f6ff9048cf0bbb72d4b4e to your computer and use it in GitHub Desktop.
Save tennisonchan/d705a1becf1f6ff9048cf0bbb72d4b4e to your computer and use it in GitHub Desktop.
Reg Extend: to extend native JS RegExp.
const regexExtract = new RegExp('\/(.*)\/([gimuy]+)?');
class RegExt extends RegExp {
constructor(input) {
if (typeof input === 'string' || input instanceof String) {
if (regexExtract.test(input)) {
let parts = regexExtract.exec(input);
super(parts[1], parts[2] || '');
} else {
super(input);
}
} else if (input instanceof RegExp) {
super(input);
}
}
toJSON() {
return this.toString();
}
}
exports = module.exports = RegExt;
@tennisonchan
Copy link
Author

tennisonchan commented Oct 25, 2017

To extend native JS RegExp on:

  • Fixing JSON.stringify(regEx) which only retruns "{}"
  • Able to get a reg string. For exmaple, new RegExt('/abc/gi') // => /abc/gi

Examples

a  = new RegExt("abc") // => /abc/
b  = new RegExt("/abc/gi") // => /abc/gi

JSON.stringify(b) // => "/abc/gi";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment