Pass Regex To JQuery Selector

前端 未结 1 609
爱一瞬间的悲伤
爱一瞬间的悲伤 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. <div id="prefix_tushar_postfix"></div>, 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');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <div id="prefix_1_postfix">prefix_1_postfix</div>
    <div id="prefix_123_postfix">prefix_123_postfix</div>
    <div id="prefix_tushar_postfix">prefix_tushar_postfix</div>
    <div id="prefix__postfix">prefix__postfix</div>
    <div id="prefix_11_postfix">prefix_11_postfix</div>
    <div id="prefix_aa_postfix">prefix_aa_postfix</div>

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