Emulating SQL LIKE in JavaScript

javascript, regex, sql, sql-like

Solution

What you have will work as long as you first escape the regex characters in your pattern. Below is one example from Simon Willison’s blog:

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

You could then implement your code as:

likeExpr = RegExp.escape(likeExpr);
var match = new RegEx(likeExpr.replace("%", ".*").replace("_", ".")).exec(str) != null;

Problem

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 supports the wildcards `%`, which matches 0 or more characters, and `_` which matches exactly one character. However, it's not just possible to do something like: ``` var match = new RegEx(likeExpr.replace("%", ".*").replace("_", ".")).exec(str) != null; ``` ...because the pattern might contain dots, stars and any other special regex characters.

Original source

Related problems