5

I'm trying to write a regex which

does not allows a number to come before or after a number like.

I have ids like this

abcd-1
abcd-11
abcd-21
...
abcd-91

I can't figure out how to write a regex that

gives me the element that have only 1

I mean abcd-1 (having no digit before and after 1). I am doing something like this

$("[id$=1]")

which gives me all the the elements from abcd-1 to abcd-91. I just neeed abcd-1.

Can you please help?

0

2 Answers 2

10

There exists a regex filter to elements selectors that you need to append to jquery:

http://james.padolsey.com/javascript/regex-selector-for-jquery/

You can then use it as below:

// Select all elements with an ID starting a vowel:
$(':regex(id,^[aeiou])');

// Select all DIVs with classes that contain numbers:
$('div:regex(class,[0-9])');

// Select all SCRIPT tags with a SRC containing jQuery:
$('script:regex(src,jQuery)');

In your case the following shall match:

 $(':regex(id,\w*-1)');

Or you can use filter with just jquery:

$('*').filter(function() {
        return this.id.match(/\w*-1/);
    }).click(function(){ //your click event code here });
Sign up to request clarification or add additional context in comments.

2 Comments

will that allow me to find the element having is abcd-1 and not all of them
You can create a regular expression to match anything you need, I have added the one that matches your case
1

You can't use a regex in a selector. (Not with just the base jQuery library, anyway.)

But you don't need regex to implement what you are describing. You are already using the "attribute ends with" selector, which finds all elements ending with the specified text without regard for what came before that text.

How about searching for ids ending in -1? As in:

$("[id$='-1']")

That will match the abcd-1 element you asked about, but not abcd-91.

2 Comments

would it solve the problem because I have no id that is ending with -1
Yes you do. You said you want to select an element with the id abcd-1, which clearly does end in -1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.