mimic
mimic

Reputation: 5234

RegEx for extracting tag attributes

Say, I have a string like

<body class="body-element" style="background: red;"><div class="inner">...</div></body>

I would like to extract all attributes of body tag. As for jQuery parsing ignores body tag I can't use it. So, how to do it using regular expressions?

I need to extract attributes only from the body tag.

Upvotes: 1

Views: 203

Answers (2)

ziggy wiggy
ziggy wiggy

Reputation: 1067

Use a DOMParser, get the .body and then its .attributes.

var s = '<body class="body-element" style="background: red;"><div>...</div></body>';

var attrs = new DOMParser().parseFromString(s, "text/html").body.attributes;

for (const a of attrs) console.log("%s = %s", a.name, a.value);

Upvotes: 3

Emma
Emma

Reputation: 27763

This RegEx might help you to divide your input HTML string into two groups and get the desired attributes:

([a-z]+)="([A-Za-z0-9_\-\:\s;]+)

You might add other chars to [A-Za-z0-9_\-\:\s;], if necessary.

enter image description here

Upvotes: 0

Related Questions