How do you check, in JavaScript, if a string is a proper regular expression that will compile?
For example, when you execute the following javascript, it produces a
The question is solved, but if someone needs to define is the string either valid RegExp or not a RegExp at all.
You can use new Function()
and templating inside of the function body with try ... catch
and new RegExp()
as mentioned earlier.
There is a snippet with the explanations:
const isRegExp = (string) => {
try {
return new Function(`
"use strict";
try {
new RegExp(${string});
return true;
} catch (e) {
return false;
}
`)();
} catch(e) {
return false;
}
};
// Here the argument 'simplyString' shall be undefined inside of the function
// Function(...) catches the error and returns false
console.log('Is RegExp valid:', isRegExp('simplyString'));
// Here the argument shall cause a syntax error
// isRegExp function catches the error and returns false
console.log('Is RegExp valid:', isRegExp('string which is not a valid regexp'));
// Here the argument is not a valid RegExp, new RegExp(...) throws an error
// Function(...) catches the error and returns false
console.log('Is RegExp valid:', isRegExp('abc ([a-z]+) ([a-z]+))'));
// Valid RegExp, passed as a string
console.log('Is RegExp valid:', isRegExp('/^[^<>()[\]\\.,;:\s@\"]$/'));
// Valid RegExp, passed as a RegExp object
console.log('Is RegExp valid:', isRegExp(/^[^<>()[\]\\.,;:\s@\"]$/));
// Howewer, the code injection is possible here
console.log('Is RegExp valid:', isRegExp(');console.log("This is running inside of the Function(...) as well"'));