Skip to content

Get ID from “ tag using a combined `.match` call

I have a string like this

`<input id="test_name" name="test_name" type="text" list="auto_search_complete" value="" placeholder="Search">`

And I just want to get the id value which is test_name. I use this code:

var str = '<input id="test_name" name="test_name" type="text" list="auto_search_complete" value="" placeholder="Search">';
var id = str.match(/id="w+"/g)[0].match(/w{3,}/g);

Is there any other ways to combine two match calls into one?

Answer

Use capturing group.

If the regular expression contain capturing group, String.prototype.match will return an array which contains whole matched string and captured groups:

str.match(/id="(w+)"/)
// ["id="test_name"", "test_name"]

You can get desired one by index:

str.match(/id="(w+)"/)[1]
// => "test_name"