Mirage
Mirage

Reputation: 31548

How to check if string is present in variable in jquery

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

Upvotes: 9

Views: 43071

Answers (4)

Ohgodwhy
Ohgodwhy

Reputation: 50767

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
}

Upvotes: 24

elclanrs
elclanrs

Reputation: 94101

Regex?

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

Upvotes: 0

Paul Armstrong
Paul Armstrong

Reputation: 7156

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

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

Upvotes: 1

jeff
jeff

Reputation: 8338

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;

Upvotes: 13

Related Questions