How can I emulate the SQL keyword LIKE in JavaScript?
For those of you who don\'t know what LIKE is, it\'s a very simple regex which only s
I was looking for an answer the same question and came up with this after reading Kip's reply:
String.prototype.like = function(search) {
if (typeof search !== 'string' || this === null) {return false; }
// Remove special chars
search = search.replace(new RegExp("([\\.\\\\\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:\\-])", "g"), "\\$1");
// Replace % and _ with equivalent regex
search = search.replace(/%/g, '.*').replace(/_/g, '.');
// Check matches
return RegExp('^' + search + '$', 'gi').test(this);
}
You can then use it as follows (note that it ignores UPPER/lower case):
var url = 'http://www.mydomain.com/page1.aspx';
console.log(url.like('%mydomain.com/page_.asp%')); // true
NOTE 29/11/2013: Updated with RegExp.test() performance improvement as per Lucios comment below.