How can I select an element by ID with jQuery using regex?

I have the following input elements:

<input id="AAA_RandomString_BBB" type="text" />
<input id="AAA_RandomString_BBB_Start" type="text" />
<input id="AAA_RandomString_BBB_End" type="text" />

AAA & BBB are constants and I will always know what they are. However RandomString will always be random.

I want to get the value of AAA_RandomString_BBB. I do not want the values from the input elements with ID ending in either _Start or _End.

I tried the folowing:

$('[id^="AAA_"]')

But the above selects all of the input elements that have an ID starting with "AAA_"

I need some way to select using a regex type syntax like:

$('[id^="AAA_(.+?)_BBB"]')

Is this possible? If not, can anyone suggest a method of selecting


Solution 1:

You can combine both selectors in a multiple attribute selector.

​$("[id^=AAA_][id$=_BBB]")

It will return all the elements that matches all the specified attribute filters:

  • [id^=AAA_] matches elements with id attribute starting with AAA_, and
  • [id$=_BBB] matches elements with id attribute ending with _BBB.

Another generic alternatives:

  • Using a custom :regex() selector,
  • Using a .filter()-based approach.

Solution 2:

Use this:

$('[id^="AAA_"][id$="_BBB"]')

Fiddle: http://jsfiddle.net/J6hGx/