Emulating SQL LIKE in JavaScript

后端 未结 9 1938
有刺的猬
有刺的猬 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:54

    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.

提交回复
热议问题