jQuery搜索字符串中的单词 [英] Jquery search word in string

查看:180
本文介绍了jQuery搜索字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有html内容,其中某些单词包含成功,失败等信息.我正在尝试使用正则表达式从多个选择复选框中过滤单个关键字或关键字组合.多选复选框的结果是一个逗号分隔的字符串.是否有条件检查我的html内容是否成功或失败或其他字符串情况.我正在尝试使用正则表达式搜索子句

I have html content where some words have success, failure etc. I am trying to use a regular expression to filter with single keyword or combination of keywords from multi selection checkboxes. The result of multi selection checkboxes is a comma separated string. Is there any condition to check if my html content has success or failure or other string cases. I am trying to search for or clause with regular expression

案例1

var filter = 'success';
$(this).html().search(new RegExp(filter, "i")) > 0) {
alert('data found')
}

情况2:

var filter = 'success, failure';
$(this).html().search(new RegExp(filter, "i")) > 0) {
alert('data found')
}

推荐答案

让我说,使用正则表达式可能是解决问题的一种解决方案,使用普通.indexOf()或就像在 @RIYAJ KHAN的答案中一样

Let me just say that using regexes for this may be a bit of a solution looking for a problem and you might get much further using plain .indexOf() or the like as in @RIYAJ KHAN’s answer…

如果您有一个包含所有要查找的单词的数组,例如:

If you have an array with all the words you’re looking for, for example:

var WORDS = ['success', 'failure'];

您可以如下创建RegExp对象:

you can create your RegExp object as follows:

var expression = new RegExp('\\b('+WORDS.join('|')+')\\b');

(在开头和结尾使用\b将确保您只匹配整个单词,这可能是为此使用正则表达式的唯一有效理由.)

(Using \b at beginning and end will ensure you only match whole words, which may be the only valid reason to use a regex for this.)

请注意,JavaScript没有从字符串中转义正则表达式特殊字符的功能,但如果您不知道字符串是否为正则表达式安全,请使用

Note that JavaScript does not have a function to escape regex special characters from strings but if you don’t know whether your strings are regex-safe or not, use this to escape the array items first.

然后搜索任何单词:

var found = expression.test($(this).text());

请注意,如果要找出匹配的单词,则必须使用String.prototype.match方法而不是String.prototype.search.

Note that if you want to find out which words matched, you’d have to use the String.prototype.match method instead of String.prototype.search.

这篇关于jQuery搜索字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆