9

I have the variable like

var myVar = "The man is running"

pattern = "run"

I want to check via jquery that if it conatins words "run"

Like

if($(myVar).(:contains(pattern)))
return true

Is this possible

2

4 Answers 4

24

RegExp option...just because..RegExp.

var pattern = /run/;

//returns true or false...
var exists = pattern.test(myVar);

if (exists) {
  //true statement, do whatever
} else {
  //false statement..do whatever
}
Sign up to request clarification or add additional context in comments.

Comments

13

You would use the Javascript method .indexOf() to do this. If you're trying to test whether the text of a DOM element contains the pattern, you would use this:

if($(myVar).text().indexOf(pattern) != -1)
    return true;

If the variable myVar isn't a selector string, you shouldn't wrap it in the jQuery function, though. Instead, you would use this:

if(myVar.indexOf(pattern) != -1)
    return true;

Comments

1

You do not need jQuery for this. Just check for the index of the string.

if (myVar.indexOf(pattern) !== -1) { ... }

Comments

0

Regex?

var hasRun = /run/i.test(myVar) // case insensitive

2 Comments

A regex has unnecessary overhead for such a simple operation, though.
Yeah, it's probably slower than indexOf but an option nonetheless and more readable, at least IMO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.