jQuery Search for Text in a Variable?

[亡魂溺海] 提交于 2019-12-14 04:28:37

问题


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

回答1:


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.




回答2:


If you are using a regular expression to search for a substring, you can find the match like this:

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

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

Note that if you are trying to search for the string "[SEARCHTERM]" (a search term containing brackets), your search method will not work because the brackets have a special meaning within regular expressions. Instead, 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 else but the search term is in the string you are checking), you should just compare the strings:

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



回答3:


What does "does not work" mean here?

Be aware that you should use braces ({}) with if statements. Some browsers will allow you to miss them out but you should include them to be correct and to support everything.



来源:https://stackoverflow.com/questions/4581625/jquery-search-for-text-in-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!