javascript 我将如何消毒这个字符串?(最好在 JQuery 中)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5840321/
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-25 18:32:32  来源:igfitidea点击:

How would I sanitize this string? (preferably in JQuery)?

javascriptjquery

提问by TIMEX

I have a webpage where people type stuff into a text box, and it displays that text below them. That's it. There is no server side.

我有一个网页,人们可以在其中在文本框中输入内容,并在其下方显示该文本。而已。没有服务器端。

Let's say someone types <script src="blah">hello</script>

假设有人打字 <script src="blah">hello</script>

I want to display that as text. Not as a script, of course. How can I do that (all in javascript)?

我想将其显示为文本。当然,不是作为脚本。我该怎么做(全部在 javascript 中)?

I want to display the entire text. Don't stip the tags out.

我想显示整个文本。不要把标签去掉。

回答by David Fells

$('div.whatever').text($('input.whatever').val());

That'll convert things to HTML entities, so they're displayed as they were typed, and not treated as markup.

这会将事物转换为 HTML 实体,因此它们在键入时显示,而不是被视为标记。

回答by icktoofay

If you want to display it in an element, you can use the textmethod. It will escape all the HTML for you.

如果要在元素中显示,可以使用text方法。它将为您转义所有 HTML。

You can see an example here.

您可以在此处查看示例。

回答by bloodcell

<input type="text" onkeyup="$('#outputDiv').text($(this).val());" />
<div id="outputDiv"></div>