Search code examples
javascriptregexpac

Check if string contains a regex & no js


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:

  1. JS in mozilla addon loads configuration as json through HTTPrequest (json contains {"something": "^(?:http|https)://(?:.*)"}
  2. JS creates a pac file(proxy configuration script) that uses the "something" regex from the configuration

Any ideas how to escape the string without destroying the regex in it?


Solution

  • 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.