Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  159] [ 1]  / answers: 1 / hits: 39010  / 14 Years ago, mon, january 3, 2011, 12:00:00

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...

More From » jquery

 Answers
28

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.


[#94407] Thursday, December 30, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nora

Total Points: 248
Total Questions: 111
Total Answers: 97

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;