Created
October 15, 2021 15:10
-
-
Save elpuas/7102f6bbd0f1c62936a814c138a71cfb to your computer and use it in GitHub Desktop.
Extract Element Attributes if DOM node props is a string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Extract Element Attributes when DOM node is a string. | |
* | |
* @author Alfredo Navas | |
* @param {string} elemText String to extract attrs. | |
* @return {object} The attributes from the string | |
*/ | |
export default function getElemAttributes(elemText) { | |
// Regex to pick out start tag from start of element's HTML. | |
let reStartTag = | |
/^<\w+\b(?:\s+[\w\-.:]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[\w\-.:]+))?)*\s*\/?>/ | |
let startTag = elemText.match(reStartTag) | |
startTag = startTag ? startTag[0] : '' | |
// Regex to pick out attribute name and (optional) value from start tag. | |
let reAttribs = /\s+([\w\-.:]+)(\s*=\s*(?:"([^"]*)"|'([^']*)'|([\w\-.:]+)))?/g | |
let attribs = {} // Store attribute name=value pairs in object. | |
let match = reAttribs.exec(startTag) | |
while (match != null) { | |
let attrib = match[1] // Attribute name in $1. | |
let value = match[1] // Assume no value specified. | |
if (match[2]) { | |
// If match[2] is set, then attribute has a value. | |
value = match[3] | |
? match[3] // Attribute value is in $3, $4 or $5. | |
: match[4] | |
? match[4] | |
: match[5] | |
} | |
attribs[attrib] = value | |
match = reAttribs.exec(startTag) | |
} | |
return attribs | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment