Jquery search word in string

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

Case 1

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

Case 2:

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

Answers 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 = (this).text().search(expression) > -1;
    

    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.


Related Articles