mrg mrg - 14 days ago 7
Javascript Question

Javascript regular expression to match id in string

Javascript:

var data='<div id="hai">this is div</div>';


Now how to write regular expression to retrive only id "hai". The expected output is,

var id = regularexpression(data);


Now id should contains "hai". Can any one help me to write regular expression in javascript ?

Answer

using regex pattern /(id="(.*?)(\"))/g

Demo

var data='<div id="hai"  class="hello">this is div</div>';
console.log(/(id="(.*?)(\"))/g.exec(data)[2])

Alternate

var data='<div id="hai" >this is div</div>';
document.body.innerHTML +=data;
var id=document.getElementsByTagName('div')[0].id;
console.log(id)

Comments