jQuery selector that simulates :starts-with or :ends-with for searching text?

前端 未结 2 1882
自闭症患者
自闭症患者 2020-12-16 15:28

If you look at the selectors list on the jQuery website, there are selectors for starts-with and ends-with on attributes. There\'s also a :contains selector for

相关标签:
2条回答
  • 2020-12-16 16:03

    When you don't want to extend jQuery, you can use the filter() function to create the contains functionality:

    $("div").find("span").filter(function () {
        return $(this).text().indexOf(text) >= 0;
    });
    

    Or create a startsWith function with a regular expression:

    var expression = new RegExp('^' + text);
    $("div").find("span").filter(function () {
        return expression.test($.trim($(this).text()));
    });
    

    The endsWith function is quite similar:

    var expression = new RegExp(text + '$');
    $("div").find("span").filter(function () {
        return expression.test($.trim($(this).text()));
    });
    

    Note the use of $.trim() because HTML can contain a lot of whitespace.

    0 讨论(0)
  • 2020-12-16 16:12

    Not by default as far as I know, but you can add your own pseudo-selectors through $.expr[":"]: http://jsfiddle.net/h6KYk/.

    $.extend($.expr[":"], {
        "starts-with": function(elem, i, data, set) {
            var text = $.trim($(elem).text()),
                term = data[3];
    
            // first index is 0
            return text.indexOf(term) === 0;
        },
    
        "ends-with": function(elem, i, data, set) {
            var text = $.trim($(elem).text()),
                term = data[3];
    
            // last index is last possible
            return text.lastIndexOf(term) === text.length - term.length;
        }
    });
    
    0 讨论(0)
提交回复
热议问题