84

Possible Duplicate:
Emulating SQL LIKE in JavaScript

Is there an operator in JavaScript which is similar to the like operator in SQL? Explanations and examples are appreciated.

Community
  • 1
  • 1
indu
  • 877
  • 1
  • 8
  • 10

6 Answers6

97

You can use regular expressions in Javascript to do pattern matching of strings.

For example:

var s = "hello world!";
if (s.match(/hello.*/)) {
  // do something
}

The match() test is much like WHERE s LIKE 'hello%' in SQL.

cletus
  • 616,129
  • 168
  • 910
  • 942
  • 18
    It's better to use `test` here (which should, by the way, be faster), since actual match result is not needed. – kangax Aug 22 '09 at 06:02
  • 3
    Most definitely, use `/regex/.test(s)` here, unless you want to do something with the matches - https://stackoverflow.com/a/10940138/1128978 – Phil Tune May 10 '19 at 17:58
41

No.

You want to use: .indexOf("foo") and then check the index. If it's >= 0, it contains that string.

Noon Silk
  • 54,084
  • 6
  • 88
  • 105
27

Use the string objects Match method:

// Match a string that ends with abc, similar to LIKE '%abc'
if (theString.match(/^.*abc$/)) 
{ 
    /*Match found */
}

// Match a string that starts with abc, similar to LIKE 'abc%'
if (theString.match(/^abc.*$/)) 
{ 
    /*Match found */
}
Ash
  • 60,973
  • 31
  • 151
  • 169
  • 1
    how to match a string based on substring, for e.g if str="john edward" then how can I use the function to return true in both cases, like if str contains john => true , if str contains edward => should return true too. – Faizan Nov 05 '13 at 12:02
  • Thanks. its very helpful. – Lova Chittumuri Jul 19 '17 at 14:25
10

You can check the String.match() or the String.indexOf() methods.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Havenard
  • 27,022
  • 5
  • 36
  • 62
3

No there isn't, but you can check out indexOf as a starting point to developing your own, and/or look into regular expressions. It would be a good idea to familiarise yourself with the JavaScript string functions.

EDIT: This has been answered before:

Emulating SQL LIKE in JavaScript

Community
  • 1
  • 1
karim79
  • 339,989
  • 67
  • 413
  • 406
-2

No, there isn't any.

The list of comparison operators are listed here.

Comparison Operators

For your requirement the best option would be regular expressions.

rahul
  • 184,426
  • 49
  • 232
  • 263
  • Please provide some quality code with examples, rather than short yes or no answers, avoiding links that can be offline in the future. – Sandro Wiggers Jun 20 '19 at 02:16