Emulating SQL LIKE in JavaScript

后端 未结 9 1930
有刺的猬
有刺的猬 2020-11-30 05:56

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

9条回答
  •  情歌与酒
    2020-11-30 06:42

    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;
    

提交回复
热议问题