Emulating SQL LIKE in JavaScript

后端 未结 9 1926
有刺的猬
有刺的猬 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 07:00

    Here's a function I use, based on PHP's preg_quote function:

    function regex_quote(str) {
      return str.replace(new RegExp("([\\.\\\\\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:\\-])", "g"), "\\$1");
    }
    

    So your line would now be:

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

提交回复
热议问题