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.
In Chris Van Opstal's answer you should use replaceAll instead of replace to replace all occurrances of '%' and '_'. Reference to how to do replaceAll - here
Johnny come lately here but this works for me I use it for my spa pages to avoid certain pages showing results after the default page:
usage is - here I want to not show any results on the tools,contact or home pages - results() is a function I do not show here:
I was looking for an answer the same question and came up with this after reading Kip's reply:
You can then use it as follows (note that it ignores UPPER/lower case):
NOTE 29/11/2013: Updated with
RegExp.test()
performance improvement as per Lucios comment below.An old question but there are actually no good answers here. TSQL LIKE expressions can contain square-bracket escaped sections that are already almost valid regular expressions and allow for matching
%
and_
. E.g.:Here's my function to convert a LIKE expression into a RegExp. The input is split into square-bracket and non-square-bracket sections. The square-bracket sections just need backslash escaping and the non-square-bracket sections are fully escaped while the
%
and_
directives are converted to regular expressions.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:
You could then implement your code as:
If you want to use a regex, you can wrap each character of the string in square-brackets. Then you only have a few characters to escape.
But a better option might be to truncate the target strings so the length matches your search string and check for equality.