简体   繁体   中英

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.

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); 

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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM