Using JavaScript regular expressions to match beginning and end of strings

This took me a little bit of time to figure out, so I thought I'd document it here so I don't have to do the research all over again.

I am working on an expression builder that allows you to create expressions for filtering a data set. One of the features allows you to create an expression that searches for values that contain, begin with, or end with a certain string. Here's a code snippet which shows functions that allow you pass in the search term as well as the data to search.

contains: function(searchFor, str){
var pattern = new RegExp(searchFor, 'gi');
return pattern.test(str);
},

beginsWith: function(searchFor, str){
var pattern = new RegExp("\^" + searchFor, 'gi');
return pattern.test(str);
},

endsWith: function(searchFor, str){
var pattern = new RegExp(searchFor + "\$", 'gi');
return pattern.test(str);
},

 

Add a Comment...