Converting URL string with query to RegEx for match( ) in Javascript

By May 6, 2017Code

match() and test() are helpful JS functions that lets you search a string for a regular expression. We recently were working on a legacy project where we had to compare a single URL against an array of URLs checking for a match. The code was written using mach(), but it wasn’t working. Essentially, it looked like this: if ( url.match( ‘^’ + urls[i] ) ) { [. . .] }. The problem was that urls was an array of strings, not the RegEx objects that match() expects.

The cool thing is that you can use JS to convert a string to a RegEx object.

for ( i in urls ) {
var regexUrl = new RegExp( '^' + urls[i] );
if ( url.match( regexUrl ) ) {
//console.log( 'matched url: ' + urls[ i ] );
return true;
}
}

The one issue we had at this point was that some of URLs had query strings (http://example.com/?query=foo&myOtherQuery=bar, e.g.). The issue was that the ‘new RegExp’ code left the question mark of the query intact, when what we needed was for it to be escaped (i.e., \? not ?). Easy! We just made use of the replace() method, escaped our escaping backspace and we were all set:

for ( i in urls ) {
urls[i] = urls[i].replace( '?', '\?' );
var regexUrl = new RegExp( '^' + urls[i] );
if ( url.match( regexUrl ) ) {
//console.log( 'matched url ' + urls[ i ] );
return true;
}
}

Leave a Reply