在javascript中打印html标签你好

问题描述 投票:0回答:4

感谢您的阅读!

var data = "<html><head><title>Hello</title></head><body>Hello Body</body></html>";

我想打印

data
包括 HTML 标签,而不让浏览器渲染 HTML 标签并只显示“Hello Body”。

我尝试过:

 
str = str.replace("<", "");

但是徒劳无功。

javascript html printing tags
4个回答
12
投票
 data = data.replace(/</g, "&lt;").replace(/>/g, "&gt;");

当浏览器遇到

&lt;
(称为字符实体)时,它会将其替换为文字 '<', enabling you to display the HTML tags on the page without them getting rendered.

/</g
是一个正则表达式,只是说“匹配所有 '<' in the string", and
g
意味着在全局范围内执行。如果没有
g
,它只会替换第一个 '<' it encounters.

最后一点,最好使用库(例如 jQuery)来执行此操作。这是一种很容易出错并错过边缘情况的东西。让经过强化、经过充分测试且安全的库函数为您做这件事。


10
投票

实际(也是更安全的修复)如下:

function htmlspecialchars(text){
    return jQuery('<div/>').text(text).html();
}

在纯 JavaScript 中,这将是:

function htmlspecialchars(text){
    var tnd=document.createTextNode(text);
    var div=document.createElement("DIV");
    div.appendChild(tnd);
    return div.innerHTML;
}

3
投票

它很难看,但你可以尝试这个(借用 Prototype 的

escapeHTML()
实现):

var data = "<html> <head> <title> Hello </title> </head> <body> Hello Body </body> </html>"
    .replace(/&/g,'&amp;')
    .replace(/</g,'&lt;')
    .replace(/>/g,'&gt;');

document.write(data);

当然创建一个小辅助函数会更好。


0
投票

回答2024

对我来说最好的是:

使用jQuery.print

© www.soinside.com 2019 - 2024. All rights reserved.