Jump to content

How to Replace HTML Tags with Named Entities using JavaScript

+ 1
  chco's Photo
Posted Jul 21 2010 03:02 PM

The following is an excerpt from Javascript Cookbook. For when you want to paste example markup into a web page, and escape the markup—have the angle brackets print out rather than have the contents parsed.
Use regular expressions to convert angle brackets (<>) into the named entities < and >:

var pieceOfHtml = "<p>This is a <span>paragraph</span></p>";
pieceOfHtml = pieceOfHtml.replace(/</g,"<");
pieceOfHtml = pieceOfHtml.replace(/>/g,">");
document.getElementById("searchResult").innerHTML = pieceOfHtml;


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, using the regular expression global flag (g) and the String replace method, as demonstrated in the solution.

Cover of Javascript Cookbook
Learn more about this topic from Javascript Cookbook. 

Covering both ECMAScript 5 and HTML5, Javascript Cookbook helps you take advantage of the latest web features, including HTML5's persistent storage mechanisms and drawing canvas. You'll find solutions for integrating these features with Javascript into UIs that people will enjoy using. The recipes in this book not only help you get things done, they'll also help you develop applications that work reliably in every browser.

Learn More Read Now on Safari


Tags:
0 Subscribe


0 Replies