Replacing HTML Tags with Named Entities

Replacing HTML Tags with Named Entities


You want to paste example markup into a web page, and escape the markup (i.e., have the angle brackets print out rather than have the contents parsed). 


Use regular expressions to convert angle brackets (<>) into the named entities &lt; and

var pieceOfHtml = "<p>This is a <span>paragraph</span></p>";

pieceOfHtml = pieceOfHtml.replace(/</g,"&lt;");

pieceOfHtml = pieceOfHtml.replace(/>/g,"&gt;");



It’s not unusual to want to paste samples of markup into another web page. The only way to have the text printed out, as is, without having the browser parse it, is to convert all angle brackets into their equivalent named entities. 

The process is simple with the use of regular expressions and the String replace method, as demonstrated in the solution. The key is to remember to use the global flag with the regular expression, to match all instances of the angle brackets. 


Post a Comment