Skip to content Skip to sidebar Skip to footer

Extract An Html Tag Name From A String

I want to extract the tag name from an HTML tag with attributes. For example, I have this tag

Solution 1:

Your regex is not matching the new line. You have to use s flag (single line) but since your regex is greedy it won't work either, also I'd remove anchors since it might be several tags in the same line.

You can use a regex like this:

<(\w+)\s+\w+.*?>

Working demo

enter image description here

Supporting Borodin's comment, you shouldn't use regex to parse html since you can face parse issues. You can use regex to parse simple tags like you have but this can be easily broken if you have text with embedded tags like <a asdf<as<asdf>df>>, in this case the regex will wronly match the tag a

The idea behind this regex is to force tags to have at least one attribute

Solution 2:

letmatchTagName = (markup) => {
  const pattern = /<([^\s>]+)(\s|>)+/return markup.match(pattern)[1]
}

matchTagName("<test>") // "test"matchTagName("<test attribute>") // "test"matchTagName("<test-dashed>") // "test-dashed"

Solution 3:

You can also try the following; it will match the tag name (always) + the attributes if they exist.

\&lt;(?&lt;name>\w+)(?&lt;attributes>\s+[^\>]*|)\>

Post a Comment for "Extract An Html Tag Name From A String"