JAVASCRIPT
Extract All Data Attributes from an HTML Tag String
Learn to efficiently extract all `data-*` attributes and their values from an HTML tag string using a powerful JavaScript regex pattern for dynamic content processing.
function extractDataAttributes(htmlTagString) {
const dataAttrRegex = /data-(\w+)="([^"]*)"/g;
let match;
const attributes = {};
while ((match = dataAttrRegex.exec(htmlTagString)) !== null) {
attributes[match[1]] = match[2];
}
return attributes;
}
// Example usage:
const tag = `<div id="myElement" data-id="123" data-type="user" data-name='John Doe' other-attr="value"></div>`;
const dataAttrs = extractDataAttributes(tag);
console.log(dataAttrs);
// Expected output: { id: '123', type: 'user' } (Note: data-name uses single quotes, not matched by current regex, could be enhanced for both)
How it works: This JavaScript function `extractDataAttributes` is designed to parse an HTML tag string and extract all its `data-*` attributes. It uses the regular expression `/data-(\w+)="([^"]*)"/g` to find all occurrences of `data-` followed by an attribute name (captured in group 1) and its value enclosed in double quotes (captured in group 2). The `while` loop iterates through all matches, populating an object where the attribute name is the key and its value is the value. This specific regex targets double quotes, which is common. For single quotes, the regex would need to be expanded.