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
-
2I feel I should recommend that you review the difference between JavaScript and jQuery. Here you can read up on JavaScript. Here you can read up on jQuery.Zhihao– Zhihao2012年07月31日 03:56:37 +00:00Commented Jul 31, 2012 at 3:56
-
Check this: @john110016 check stackoverflow.com/questions/4581625/… is exactly like your questionsMarco Pappalardo– Marco Pappalardo2012年07月31日 03:58:56 +00:00Commented Jul 31, 2012 at 3:58
4 Answers 4
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
}
Comments
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
You do not need jQuery for this. Just check for the index of the string.
if (myVar.indexOf(pattern) !== -1) { ... }
Comments
Regex?
var hasRun = /run/i.test(myVar) // case insensitive