1

I have the following html tag (which is custom):

<meltdown-code data-lang="HTML">
    <span><br>
        <p>Hi</p><br>
    </span><br>
</meltdown-code>

Simple enough. Now, I'm trying to make the HTML tags show as plain text, instead of being rendered as a separate element. To do that, I am replacing all the < with &lt;, and all the > with &gt;

tagHTML.replace(/</g, '&lt;')

The problem: This also replaces the <br> tags, which doesn't create a new line. Here is the solution, in a perfect world:

tagHTML.replace(/</g, '&lt;', {exceptions: '<br>'})

Obviously, that's not how it works. Any help is appreciated.

Thanks!

3
  • Have a look at negative lookaheads! Commented Sep 24, 2022 at 23:25
  • @caTS, thanks for your instant reply! I will check them out and get back to you Commented Sep 24, 2022 at 23:25
  • @caTS, sorry... I'm not sure I understand. I'm not really good with regex. Would you mind explaining it to me? Commented Sep 24, 2022 at 23:27

1 Answer 1

2

Negative lookahead for <br> before matching <.

const text = `<meltdown-code data-lang="HTML">
    <span><br>
        <p>Hi</p><br>
    </span><br>
</meltdown-code>`;

const output = text.replace(/(?!<br>)<([^>]+)>/g, '&lt;$1$gt;');
console.log(output);
<code></code>

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, thanks! There's no way I would have been able to write that Regex on my own lol. I'll accept when i can :D
@caTS My first time working with Regex 🤣🤣🤣

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.