Jquery Search Word In String
Solution 1:
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'];
you can create your RegExp object as follows:
var expression = new RegExp('\\b('+WORDS.join('|')+')\\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.)
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.
Then search for any word:
var found = expression.test($(this).text());
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
.
Solution 2:
Define one array containig your expected string
var arrString = ["success","failure"];
As you say,multi selection checkboxes is a comma separated string.
So, I am assuming like this.
var arrHtml = "success,test,test2,failure"; ////$(this).html()
arrHtml.split(",").some(function(val, index) {
return arrString.indexOf(val) >= 0
})
OR ECMA6 :
arrHtml.split(",").some((val,index)=> arrString.indexOf(val)>=0 )
Solution 3:
try
var filter = '(success)|(failure)';
$(this).html().search(newRegExp(filter, "i")) > 0) {
alert('data found')
}
Post a Comment for "Jquery Search Word In String"