Pass Regex To JQuery Selector

2019-01-29 05:44发布

问题:

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")

My elements have ids as follows prefix_10_postfix prefix_1_postfix

Kindly guide me.

回答1:

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>