The variable htmlStr may contain different spellings of id:
var htmlStr = "<div id="demo_div"></div>";
var htmlStr = "<div id='demo_div'></div>";
var htmlStr = "<div id=demo_div class="demo"></div>";
var htmlStr = "<div id=demo_div></div>";
How can I write this differently without many try-catch functions? Can I combine the patterns? It works - but does not look pretty.
var idname;
try {
idname = /(id="(.*?)(\"))/g.exec(htmlStr)[2]
} catch (e) {
try {
idname = /(id='(.*?)(\'))/g.exec(htmlStr)[2]
} catch (e) {
try {
idname = /(id=(.*?)(\ ))/g.exec(htmlStr)[2]
} catch (e) {
try {
idname = /(id=(.*?)(\>))/g.exec(htmlStr)[2]
} catch (e) {
console.log(e);
}
}
}
}
console.log(idname);


execdoesn't throw an error if no match is found(id=['"]?(.*?)["'> ])/id=(?:(["'])([^'"]*)\1|([^\s>]*))/g, loop over all matches by callingexecuntil no match, and only grab either Group 2 or Group 3 (if Group 3 matched). But it is safer to use a DOM parser to parse HTML.