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
How do I escape a single quote?
提问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 实体:
'
for'
"
for"
- ...
'
为了'
"
为了"
- ...
For more, you can take a look at Character entity references in HTML.
有关更多信息,您可以查看HTML 中的字符实体引用。
回答by Benjamin Manns
You can use '
(which is iffy in IE) or '
(which should work everywhere). For a comprehensive list, see the W3C HTML5 Named Character Referencesor the HTML entities table on WebPlatform.org.
您可以使用'
(在 IE 中不确定)或'
(在任何地方都可以使用)。有关完整列表,请参阅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'
('
hexadecimal):
由于您处于 HTML 的上下文中,因此您需要使用 HTML 来表示该字符。对于 HTML,您需要使用数字字符引用'
('
十六进制):
<input type='text' id='abc' value='hel'lo'>
回答by AndiDog
Represent it as a text entity (ASCII 39):
将其表示为文本实体 (ASCII 39):
<input type='text' id='abc' value='hel'lo'>
回答by road242
Probably the easiest way:
可能是最简单的方法:
<input type='text' id='abc' value="hel'lo">
回答by thelost
You could try using: ‘
您可以尝试使用: ‘
回答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 数据要在属性中使用,这将很有帮助