gmustudent gmustudent - 13 days ago 6
Javascript Question

How to build a regex w/ new RegExp()

Have an array of local storage keys that looks something like this

[
'$gl-user',
'$gl-date-preference::22'
'$gl-date-preference::28'
'$gl-mg-filters::22::1'
'$gl-mg-filters::22::8'
]



  • First
    ::_number_
    represents the
    storeId
    .

  • Second
    ::_number_
    can
    represents any additional identifier.



Trying to build a function that takes a
storeId
and returns all keys that match that
storeId
. So if
22
was passed in to that function it would return

[
'$gl-date-preference::22',
'$gl-mg-filters::22::1',
'$gl-mg-filters::22::8'
]


Here is my first attempt. Copying this into the console returns null every time but I do not understand why.

var regex = new RegExp('^[$\w\d\-]+\:\:' + '22');
'$gl-mg-filters::22'.match(regex);


Any assistance in getting this regex to work, or ideas on a better solution would be greatly appreciated. Thank you!

Answer

Your regex isn't matching, because you're only escaping with the slashes inside of the string. Instead, you should be escaping it twice, e.g.:

var regex = new RegExp('^[$\\w\\d\\-]+\\:\\:' + '22');
'$gl-mg-filters::22'.match(regex);

Your initial attempt would try to compile ^[$wd-]+::22 into a Regex.

Comments