HomeJavaScriptReplace HTML tags with named entities in JavaScript

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;");


Leave a Reply

You May Also Like

You might want to filter an array in JavaScript by passing the filter criteria and return the filtered array. In...
You can flatten a 2-D array in JavaScript using the concat and apply method as shown in the below code...
Assume that you have an angle in degree and you wish to convert it to radians in JavaScript so that...