Is there a case insensitive jQuery :contains selector?

后端 未结 12 2135
悲哀的现实
悲哀的现实 2020-11-22 02:45

Is there a case insensitive version of the :contains jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?<

12条回答
  •  借酒劲吻你
    2020-11-22 02:55

    A variation that seems to perform slightly faster and that also allows regular expressions is:

    jQuery.extend (
        jQuery.expr[':'].containsCI = function (a, i, m) {
            //-- faster than jQuery(a).text()
            var sText   = (a.textContent || a.innerText || "");     
            var zRegExp = new RegExp (m[3], 'i');
            return zRegExp.test (sText);
        }
    );
    



    Not only is this case-insensitive, but it allows powerful searches like:

    • $("p:containsCI('\\bup\\b')") (Matches "Up" or "up", but not "upper", "wakeup", etc.)
    • $("p:containsCI('(?:Red|Blue) state')") (Matches "red state" or "blue state", but not "up state", etc.)
    • $("p:containsCI('^\\s*Stocks?')") (Matches "stock" or "stocks", but only at the start of the paragraph (ignoring any leading whitespace).)

提交回复
热议问题