Janet Riley

Javascript Regular Expression with a variable

December 01, 2014 | In 30 days / javascript

Regular expressions let us detect when a string matches a pattern. It's straightforward to make a hardcoded regular expression. This will show whether a phrase starts with a capital T:

    /^T/

But what if you don't know the pattern ahead of time, like in a search form? What's the syntax when you're using a variable?

I needed to find all the array elements that began with a phrase the user selected. Here's the snippet:

function startsWith(compareTo, value ){
    var startsWithRegExp = new RegExp('^' + compareTo);
    return startsWithRegExp.test(value);
  }

The important bit is the RegExp constructor on line 2. Build up the pattern like a normal string, and omit the beginning and ending slashes.

And here's how to filter the array.

  var lookFor = 'T';
  var candidates = ['Trouble', 'River City', 'Pool', 'Tempest in a Teapot'];
  var matches = candidates.filter( function(value){ return startsWith(lookFor, value )});