Reputation: 31548
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
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
Reputation: 7156
You do not need jQuery for this. Just check for the index of the string.
if (myVar.indexOf(pattern) !== -1) { ... }
Upvotes: 1
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