首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不使用innerHTML的转义字符

不使用innerHTML的转义字符
EN

Stack Overflow用户
提问于 2015-04-09 03:57:32
回答 2查看 2.8K关注 0票数 1

我有一个字符串,其中包含HTML转义字符(用于<>),我试图使用innerHTML在div中呈现这些字符。转义字符不应呈现为普通html,而应呈现为文本。然而,他们仍然这样做,因此,是否有一个工作围绕这一点?

注意:目标是以普通文本的形式显示几个(意思不是全部)标记。

下面是一个实现示例:

代码语言:javascript
运行
复制
var string = "<div>yolo</div>";

string = string.replace(/</g, '&lt;'); //replaces all '<' with its escape character
string = string.replace(/>/g, '&gt;'); //replaces all '>' with its escape character

string = string.replace(/(=|%|\/|\*|-|,|;|\+|<|>)/g, "<span class=\"sc\">$1</span>");

//the last line adds special formatting 
//to certain characters using CSS (not shown)
//and a span tag with class, "sc".
//this is the reason that I cannot just simply
//use innertext instead of innerhtml

document.body.innerHTML = string;

P.S.请用纯JavaScript回答。我不在乎您是否添加了一个jQuery解决方案,我只需要一个纯的javascript解决方案。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-09 04:04:49

它不能正常工作,因为您要用;替换<spans>。尝试首先替换整个&lt;,以防止span替换器破坏实体。

例如:

代码语言:javascript
运行
复制
var string = "<div>yolo</div>";

string = string.replace(/</g, '&lt;'); //replaces all '<' with its escape character
string = string.replace(/>/g, '&gt;'); //replaces all '>' with its escape character

string = string.replace(/(&lt;|&gt;|=|%|\/|\*|-|,|;|\+|<|>)/g, "<span class=\"sc\">$1</span>");

//the last line adds special formatting 
//to certain characters using CSS (not shown)
//and a span tag with class, "sc".
//this is the reason that I cannot just simply
//use innertext instead of innerhtml

document.body.innerHTML = string;
代码语言:javascript
运行
复制
.sc {
    color: red;
    font-weight: bold;
}

票数 4
EN

Stack Overflow用户

发布于 2015-04-09 04:00:28

如果使用jQuery,您可能需要处理text()而不是innerHTML()

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29529472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档