Address
c/o CoWork, The Cotton Factory
270 Sherman Ave N Suite #301
Hamilton, ON
L8L 6N4

Work Hours (Eastern)
M, Tu, Th, F: 9am – 5pm
W, Sa, Su: Various

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

A quick tutorial on working with match(), test(), strings and regex objects in JavaScript, including how to escape your query strings.

[vc_row type=”in_container” full_screen_row_position=”middle” scene_position=”center” text_color=”dark” text_align=”left” overlay_strength=”0.3″][vc_column column_padding=”no-extra-padding” column_padding_position=”all” background_color_opacity=”1″ background_hover_color_opacity=”1″ width=”1/1″ tablet_text_alignment=”default” phone_text_alignment=”default”][vc_column_text]match() and test() are helpful JS functions that let 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;
}
}
[/vc_column_text][/vc_column][/vc_row]

Leave a Reply

Your email address will not be published. Required fields are marked *