Deleting HTML tags in Discord message

Hi, glitchers! There is a Discord message: <p> Test message </p>

How to remove <p> and </p>?

I would use a regex that removes anything between < and >.

discordMessage.replace(/<.+?>/g, "")

This regex looks for anything matching <.+?> and removes it (replaces it with an empty string).

Quick breakdown of what the regex is doing:

  • Regexes are surrounded by / characters
  • The < and > match literal characters
  • . matches any character, and + matches one or more. So .+ means “one or more of any character”
  • The ? makes the .+ “lazy”, meaning that it’ll make the .+ as short as possible. Without this, the regex would delete the whole message, because the entire message starts with < and ends with >. We want the regex to match the smallest possible part in between < and >, hence the ? character
  • The g at the end means “global”, so it’ll match multiple of this pattern

You can test this pattern regex here: https://regex101.com/r/GUxMca/1

2 Likes