在 jQuery 或 JavaScript 中转义单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5083646/
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
Escape single quotes in jQuery or JavaScript
提问by Someone
I want to display the following text for the <span>
tag. How do I escape the single quotes for the following?
我想为<span>
标签显示以下文本。如何转义以下单引号?
$("#spn_err").text($('#txt1').attr('value')+" is not valid");
I want to display the message as 'ZZZ' is not valid
. Here $('#txt1').attr('value')
is a dynamic value. It may have abc
, bcc
, ddd
, zzz
. How can I do this?
我想将消息显示为 ' ZZZ' is not valid
。这$('#txt1').attr('value')
是一个动态值。它可能有abc
, bcc
, ddd
, zzz
。我怎样才能做到这一点?
回答by Felix Kling
Like this:
像这样:
$("#spn_err").text("'" + $('#txt1').val() + "' is not valid");
Inside double quotes, single quotes are normal characters and vice versa. Otherwise you can escape them by prepending a backslash: "\""
or '\''
.
在双引号内,单引号是普通字符,反之亦然。否则,您可以通过在前面加上反斜杠来转义它们:"\""
或'\''
。
回答by C. Spencer Beggs
$("#spn_err").text('\'' + $("#txt1").attr("value") + '\' is not valid');
回答by Stephen
回答by amit_g
$("#spn_err").text("'" + $('#txt1').attr('value') + "' is not valid");