2

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
  • Note here that in regex [\d]{1, 2} can be used as \d{1,2}, no need of class and space Commented Oct 24, 2015 at 4:34

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.