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...
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.If you were hoping for an exact match, which your use of
^and$seems to imply, you could just do an===comparison.EDIT: Based on your comment, you want an exact match, but
===isn’t working, whileindexOf()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.If this doesn’t work, I’d recommend logging
this.textto the console to see if it is the value you expect.