简体   繁体   English

在jQuery或JavaScript中转义单引号

[英]Escape single quotes in jQuery or JavaScript

I want to display the following text for the <span> tag. 我想为<span>标记显示以下文本。 How do I escape the single quotes for the following? 如何逃避以下单引号?

$("#spn_err").text($('#txt1').attr('value')+" is not valid");

I want to display the message as ' ZZZ' is not valid . 我想显示消息,因为' ZZZ' is not valid Here $('#txt1').attr('value') is a dynamic value. 这里$('#txt1').attr('value')是一个动态值。 It may have abc , bcc , ddd , zzz . 它可能有abcbccdddzzz How can I do this? 我怎样才能做到这一点?

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 '\\'' . 否则你可以通过添加反斜杠来逃避它们: "\\""'\\''

$("#spn_err").text('\'' + $("#txt1").attr("value") + '\' is not valid');

It is close. 它很接近。 Use the .val() method: 使用.val()方法:

$('#spn_err').text($('#txt1').val() + ' is not valid');
$("#spn_err").text("'" + $('#txt1').attr('value') + "' is not valid");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM