JQuery text search in a variable?

I have a variable that contains some text, some html, basically it could be a string. I need to look for a variable for a particular string to handle this variable differently if it is contained. Here is a snippet of what I'm trying to do does not work explicitly :)

$.each(data.results, function(i, results) { var text = this.text var pattern = new RegExp("^[SEARCHTERM]$"); if(pattern.test( text ) ) alert(text); //was hoping this would alert the SEARCHTERM if found... 
+7
source share
3 answers

Instead, you can use .indexOf() to perform a search.

If the string is not found, it returns -1 . If it is found, it returns the first null index where it was located.

 var text = this.text; var term = "SEARCHTERM"; if( text.indexOf( term ) != -1 ) alert(term); 

If you were hoping for an exact match, which apparently implies using ^ and $ , you can simply compare === .

 var text = this.text; var term = "SEARCHTERM"; if( text === term ) alert(term); 

EDIT:. Based on your comment, you want to get an exact match, but === doesn't work, and indexOf() -. This sometimes happens if there are some spaces that need to be trimmed.

Try trimming spaces with the jQuery jQuery.trim() method.

 var text = $.trim( this.text ); var term = "SEARCHTERM"; if( text === term ) alert(term); 

If this does not work, I recommend logging this.text in the console to find out if this is the expected value.

+9
source

If you use a regular expression to search for a substring, you can find a match as follows:

 var match = text.match(pattern); if(match) { alert(match[0]); } 

See the documentation for .match() for more information.

Please note: if you try to find the string "[SEARCHTERM]" (a search query containing brackets), your search method will not work because the brackets have special meaning in regular expressions. Use .indexOf() :

 var index = text.indexOf("[SEARCHTERM]"); if(index != -1) { alert("Search term found"); } 

However, if you are just trying to find an exact match (nothing but a search term in the string you are checking), you should simply compare the strings:

 if(text == "[SEARCHTERM]") { alert("Search term found"); } 
+2
source

What does "not work" mean?

Remember that you must use curly braces ( {} ) with if . Some browsers allow you to skip them, but you must include them in the correct ones and support everything.

0
source

All Articles