Skip to content Skip to sidebar Skip to footer

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 = '

Solution 1:

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!


Solution 2:

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.


Post a Comment for "Extract An ID Value From A String With JavaScript"