Pass Regex To JQuery Selector

前端 未结 1 635
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-20 03:51

Hi I have following scenario. I have working regex but cant pass it to jQuery selectors. I am trying following.

$(\"#prefix_[\\d]{1, 2}_postfix\")

1条回答
  •  忘掉有多难
    2020-12-20 04:13

    You can use starts with and ends with attribute-value selector

    $('[id^="prefix_"][id$="_postfix"]')
    

    This will select all the elements whose id starts with prefix_ and ends with _postfix.


    If the page contains many elements whose id starts with prefix_ and ends with _postfix but doesn't match the criteria that in between them should be one or two numbers, ex.

    , the starts with and ends with selector will not work. In this case filter can be used in combination with attribute selectors.

    Demo

    var regex = /^prefix_\d{1,2}_postfix$/;
    
    // Narrow down elements by using attribute starts with and ends with selector
    $('[id^="prefix_"][id$="_postfix"]').filter(function() {
      
      // filter the elements that passes the regex pattern
      return regex.test($(this).attr('id'));
    }).css('color', 'green');
    
    
    prefix_1_postfix
    prefix_123_postfix
    prefix_tushar_postfix
    prefix__postfix
    prefix_11_postfix
    prefix_aa_postfix

    0 讨论(0)
提交回复
热议问题