[Edit]
+
0
-
0
js escape html special characters example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39<!doctype html> <html> <body> <script> var HTMLUtils = new function() { var rules = [ { expression: /&/g, replacement: '&' }, // keep this rule at first position { expression: /</g, replacement: '<' }, { expression: />/g, replacement: '>' }, { expression: /"/g, replacement: '"' }, { expression: /'/g, replacement: ''' } // or ' or ' // ' is not supported by IE8 // ' is not defined in HTML 4 ]; this.escape = function(html) { var result = html; for (var i = 0; i < rules.length; ++i) { var rule = rules[i]; result = result.replace(rule.expression, rule.replacement); } return result; } }; // Usage example: var escapedHtml = HTMLUtils.escape('<div class="item">Hi! How are you?</div>'); // Printing in body: document.body.innerHTML = escapedHtml; // we can display it as text too // Printing in console: console.log(escapedHtml); // <div class="item">Hi! How are you?</div> </script> </body> </html>