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?
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?
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)./
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)')
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.
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.
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.