87

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.

1

6 Answers 6

102

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's better to use test here (which should, by the way, be faster), since actual match result is not needed.
Most definitely, use /regex/.test(s) here, unless you want to do something with the matches - stackoverflow.com/a/10940138/1128978
42

No.

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

2 Comments

If the case is different, it will not work. You need to use: myString.toLowerCase().indexOf("foo")
On integers use toString() first. myInteger.toString().indexOf(value) > -1.
29

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 */ } 

1 Comment

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.
10

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

Comments

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

Comments

-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.

1 Comment

Please provide some quality code with examples, rather than short yes or no answers, avoiding links that can be offline in the future.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.