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

Zhihao
14.7k2 gold badges29 silver badges36 bronze badges
asked Jul 31, 2012 at 3:50
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
}
answered Jul 31, 2012 at 4:03
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;
answered Jul 31, 2012 at 3:53

Comments

1

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

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

answered Jul 31, 2012 at 3:55

Comments

0

Regex?

var hasRun = /run/i.test(myVar) // case insensitive
answered Jul 31, 2012 at 3:57

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.