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...
var text = this. text; var term = "SEARCHTERM"; if( text. indexOf( term ) != -1 ) alert(term);
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With