views:

2701

answers:

5

Hello guys, thanks for the help in advance.

How can I have jquery check to see if a variable contains a specific word in it and have it execute an alert if matched?

A: 

One word: Regular expressions.

Whoops, that were 2 words ;)

https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FGuide/Regular%5FExpressions

Regex:

/.(mystring\swhich\sshould\smatch)./
Time Machine
It should be noted, for the askers understanding, that this solution is plain javascript, and this problem doesn't need/use jquery.
TM
+7  A: 
if( str.indexOf( "your word" ) !== -1 )

or

if( str.search( /your regex/ig ) )

or

if( str.match( /your regex/ig ).length > 0 )

As it shows, you do not need jQuery to solve this problem.

But, hell, why not use jQuery selectors if you want:

$('#someId:contains(text)')
geowa4
+1 It should be noted, for the askers understanding, that these solutions are plain javascript, and this problem doesn't need/use jquery.
TM
The indexOf-solution should be the most efficient one.
Jan Aagaard
@Jan: it probably would, especially if one is only looking for a known string. but the regex is better in more cases due to its flexibility
geowa4
AFAIK, Internet Explorer (6, at least) doesn't have `indexOf`
nickf
+1  A: 

If you are looking to check a javascript variable and not some element on the page, jQuery isn't going to really make it any easier/different than using plain javascript.

The other answers mentioned here using regex will work, but you might want to look at the String object reference or the RegExp object reference at w3schools, if you want to understand it better.

TM
thank you very much for the reply, this answered helped me a ton. I looked at .test
Ronal
A: 

For an element, use String functions on its name or whatever other applicable attribute value:

if(jQuery("elementName").attr("attributeName").contains(...))
  callSomeJSFunction();

, or Regular Expressions. If it's something simple, string manipulation should be sufficient as other people have mentioned. Another great resource are the jQuery API pages or countless other tutorials found through a Google search. Google's groups are often another useful resource.

raptors
A: 

The str.match() and str.indexOf() functions as intimated by geowa4 will do you just fine if you are looking in standard JavaScript strings. In fact this is not actually jQuery at all (jQuery doesn't replace everything we would normally do in JavaScript).

If you are looking for text within a jQuery variable, then you may want to look at the .contains() function for example

var bExists = $("#MySelection").contains("text");

This will ignore any embedded tags, i.e. it will act as if they have been stripped out of the search area completely.

James Wiseman