如何使用 javascript 将 html 标签转换为普通字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8712751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:19:11  来源:igfitidea点击:

How do i convert html tags to normal string using javascript?

javascriptjqueryhtml

提问by Avihay Menahem

Possible Duplicate:
Convert tags to html entities

可能的重复:
将标签转换为 html 实体

I am building a snippets area to a friend's site, and i need to know how to convert html tags to normal text so the page will show the tags.

我正在为朋友的网站构建一个片段区域,我需要知道如何将 html 标签转换为普通文本,以便页面显示标签。

Like here in the code:

就像这里的代码:

<img>

so the tag will be seen and not become to a normal html tag,

所以标签将被看到,而不是变成一个普通的 html 标签,

And all this using javascript or jQuery.

而这一切都使用 javascript 或 jQuery。

What I got now is something like that:

我现在得到的是这样的:

<pre><code>THE USERS CODE</code></pre>

and it still hide the html tags and make them active. thx :)

它仍然隐藏 html 标签并使它们处于活动状态。谢谢 :)

回答by Wes Crow

You could use

你可以用

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

SOURCE: http://css-tricks.com/snippets/javascript/htmlentities-for-javascript/

来源:http: //css-tricks.com/snippets/javascript/htmlentities-for-javascript/

回答by Leigh Ciechanowski

Use Jquery and instead of $('something').html()use $('something').text()checkout http://api.jquery.com/text/

使用 Jquery 而不是$('something').html()使用$('something').text()结帐http://api.jquery.com/text/