Search code examples
regexstringify

Javascript Storing Regexp screws the original format


I have an angular app where a user can add a regexp in a form, a value like:

github\.com/([A-Za-z0-9\-\_]+)/([A-Za-z0-9\-\_]+)

When I store this in the localStorage and I inspect the localStorage:

github\\\\.com\\/([A-Za-z0-9\\\\-\\\\_]+)\\/([A-Za-z0-9\\\\-\\\\_]+)

When I retrieve in Javascript elsewhere this value I get:

github\\.com\/([A-Za-z0-9\\-\\_]+)\/([A-Za-z0-9\\-\\_]+)

This is not the original regexp and the match method in Javascript can't work.

NOTE: after submitting the form, I store the object with:

localStorage.myobject = JSON.stringify(myobject);

Solution

  • You can get rid of overescaping here, just use

    github[.]com/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)
    

    and initialize it via a RegExp constructor so as not to have to escape the regex delimiter /. A dot inside [] loses its special meaning and only matches a literal dot, the hyphen at the end of the character class only matches a literal hyphen, and the _ does not have to be escaped at all anywhere in the pattern:

    var tst = "github.com/Test1-Text/Test2";
    var pattern = "github[.]com/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)";
    console.log(new RegExp(pattern).test(tst));

    UPDATE:

    When using patterns from external sources, you need to use the constructor notation. Make sure your regex patterns are stored as literal strings (if you had RegExp("C:\\\\Folder"), make sure it is stored as C:\\Folder), and when reading the value in it will be automatically be usable with the RegExp constructor.