I have a string and I need to make sure that it contains only a regular expression and no javascript because I'm creating a new script with the string so a javascript snippet would be a security risk.
Exact scenario:
Any ideas how to escape the string without destroying the regex in it?
It seems that most of the standard JavaScript functionality is available (source), so you can just do:
try {
RegExp(json.something+'');
pacFile += 'RegExp(' + JSON.stringify(json.something+'') + ')';
} catch(e) {/*handle invalid regexp*/}
And not worry, because a RegExp("console.log('test')")
will only produce a valid /console.log('test')/
regexp and execute nothing.