Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Search for Text in a Variable?

I have a variable that contains some text, some html, basically can be a string. I need to search the variable for a specific string to process that variable differently if it is contained. Here is a snippet of what I am trying to do, does not work obviously :)

$.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...
like image 225
thatryan Avatar asked Jan 03 '11 02:01

thatryan


People also ask

How to check the string in the variable in jQuery?

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

How do I search for a specific word in a string using jQuery?

How to find if a word or a substring is present in the given string. In this case, we will use the includes() method which determines whether a string contains the specified word or a substring. If the word or substring is present in the given string, the includes() method returns true; otherwise, it returns false.

How use contains in jQuery?

jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

How to search word in javascript?

The search() method returns the index (position) of the first match. The search() method returns -1 if no match is found. The search() method is case sensitive.


1 Answers

You could use .indexOf() instead to perform the search.

If the string is not found, it returns -1. If it is found, it returns the first zero-based 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 your use of ^ and $ seems to imply, you could just do an === comparison.

var text = this.text;
var term = "SEARCHTERM";

if( text === term )
    alert(term);

EDIT: Based on your comment, you want an exact match, but === isn't working, while indexOf() is. This is sometimes the case if there's some whitespace that needs to be trimmed.

Try trimming the whitespace using jQuery's jQuery.trim() method.

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

if( text === term )
    alert(term);

If this doesn't work, I'd recommend logging this.text to the console to see if it is the value you expect.

like image 160
user113716 Avatar answered Nov 11 '22 16:11

user113716