Html 如何转义单引号?

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

How do I escape a single quote?

htmlescaping

提问by Ravi

How can I escape a '(single quote) in JavaScript?

如何'在 JavaScript 中转义(单引号)?

This is where I'm trying to use it:

这是我尝试使用它的地方:

<input type='text' id='abc' value='hel'lo'>

The result for the above code is "hel" populated in the text box. I tried to replace ' with \', but this what I'm getting.

上述代码的结果是在文本框中填充了“hel”。我试图用 \ 替换 ',但这就是我得到的。

<input type='text' id='abc' value='hel\'lo'>

The result for the above code is "hel\" populated in the text box.

上述代码的结果是在文本框中填充了“hel\”。

How can I successfully escape the single quotes?

如何成功转义单引号?

回答by Pascal MARTIN

You could use HTML entities:

您可以使用 HTML 实体:

  • &#39;for '
  • &#34;for "
  • ...
  • &#39;为了 '
  • &#34;为了 "
  • ...

For more, you can take a look at Character entity references in HTML.

有关更多信息,您可以查看HTML 中的字符实体引用

回答by Benjamin Manns

You can use &apos;(which is iffy in IE) or &#39;(which should work everywhere). For a comprehensive list, see the W3C HTML5 Named Character Referencesor the HTML entities table on WebPlatform.org.

您可以使用&apos;(在 IE 中不确定)或&#39;(在任何地方都可以使用)。有关完整列表,请参阅W3C HTML5 命名字符参考WebPlatform.org 上HTML 实体表

回答by Gumbo

As you're in the context of HTML, you need to use HTML to represent that character. And for HTML you need to use a numeric character reference&#39;(&#x27;hexadecimal):

由于您处于 HTML 的上下文中,因此您需要使用 HTML 来表示该字符。对于 HTML,您需要使用数字字符引用&#39;&#x27;十六进制):

<input type='text' id='abc' value='hel&#39;lo'>

回答by AndiDog

Represent it as a text entity (ASCII 39):

将其表示为文本实体 (ASCII 39):

<input type='text' id='abc' value='hel&#39;lo'>

回答by road242

Probably the easiest way:

可能是最简单的方法:

<input type='text' id='abc' value="hel'lo">

回答by thelost

You could try using: &#145;

您可以尝试使用: &#145;

回答by Ram Bharlia

use javascript inbuild functions escape and unescape

使用 javascript inbuild 函数 escape 和 unescape

for example

例如

var escapedData = escape("hel'lo");   
output = "%27hel%27lo%27" which can be used in the attribute.

again to read the value from the attr

var unescapedData = unescape("%27hel%27lo%27")
output = "'hel'lo'"

This will be helpful if you have huge json stringify data to be used in the attribute

如果您有大量 json stringify 数据要在属性中使用,这将很有帮助