JasonDavis
JasonDavis

Reputation: 48933

Extract an ID value from a string with JavaScript

IN a JavaScript Event I only have access to a string in this format below...

var innerHTML = '<img src="https://avatars3.githubusercontent.com/u/7988569?v=3&amp;s=40"
class="item-image picker-item-thumb"><i id="2">Item 2</i>';

I need to extract the ID value from this part <i id="2"> so I would have 2 in a variable.

Also none of the other HTML tags will ever have an ID besides the <i>

I'm not sure how to do this?

Upvotes: 1

Views: 1979

Answers (2)

aarjithn
aarjithn

Reputation: 1181

Use regex capturing group.

If the id is always numeric, use:

/<i id="(\d+)"/.exec(innerHTML)[1]

Else, you can use

/<i id="([^"]+)"/.exec(innerHTML)[1]

Suggest to look at the comments for further information!

Upvotes: 2

Nishanth Matha
Nishanth Matha

Reputation: 6081

You can use regex to do it:

(?<=i id=").+(?=")

As pointed by felix king you can try the following as javascript doesn't support lookbehinds:

/i id="(.+)"/

var innerHTML = '<img src="https://avatars3.githubusercontent.com/u/7988569?v=3&amp;s=40"
class="item-image picker-item-thumb"><i id="2">Item 2</i>';
var arr = innerHTML.match(/i id="(.+)"/)[1];
alert(arr);

arr will have all the matches.

Upvotes: 0

Related Questions