Replacing HTML Tags with Named Entities
Problem
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).
Solution
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,">"); console.log(pieceOfHtml);
EXPLAIN
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.
No comments:
Post a Comment