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

Your email address will not be published. Required fields are marked *

You May Also Like

JavaScript supports different types of operators that includes Assignment Operator JavaScript supports different types if Assignment Operators like = +=...
Assume that you have an angle in degree and you wish to convert it to radians in JavaScript so that...
The JavaScript elements and statements are placed within the script tag within the HTML page. You can specify the language...