Replace HTML tags with named entities in JavaScript

There are times when you might want to paste the code snippet in to a webpage. Imagine if that code snippet contains the HTML tags and somehow you want to escape the markup code without the browser parsing it. An idea for this would be to use convert the angle brackets to its equivalent named entities like < and >.

You can use the combination of the string’s replace method and regular expression as shown below. Just use the global flag in the regular expression so that all the instances of the angle brackets are found and replaced with their named entities.

How to replace HTML tags with named entities in JavaScript ?

<script type="text/javascript">
    var inputStr = "<pre>This blog post is written by <h1> Senthil </h1></pre>";
    inputStr = inputStr.replace(/</g, "&lt;");
    inputStr = inputStr.replace(/>/g, "&gt;");
    console.log(inputStr);
</script>

image

Leave a Reply