jQuery在变量中搜索文本? [英] jQuery Search for Text in a Variable?
问题描述
我有一个包含一些文本的变量,一些html,基本上可以是一个字符串。我需要在变量中搜索特定字符串,以便在包含该变量时以不同方式处理该变量。以下是我要做的事情的片段,显然不起作用:)
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...
推荐答案
您可以使用 .indexOf()
代替执行搜索。
You could use .indexOf()
instead to perform the search.
如果找不到该字符串,则返回 -1
。如果找到,则返回第一个从零开始的索引它所在的位置。
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);
编辑:基于在你的评论中,你想要一个完全匹配,但 ===
不起作用,而 indexOf()
是。如果有一些需要修剪的空白,有时会出现这种情况。
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);
如果这不起作用,我建议记录 this.text
到控制台查看它是否是您期望的值。
If this doesn't work, I'd recommend logging this.text
to the console to see if it is the value you expect.
这篇关于jQuery在变量中搜索文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!