代码如下:

function htmlEntities(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

代码整理自:https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/

Related Posts: PHP的htmlEntities在JavaScript如何实现 :