开发者

Escape single quotes in jQuery or JavaScript

I want to display the following text for the <span> tag. 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 v开发者_如何学Calid. Here $('#txt1').attr('value') is a dynamic value. It may have abc, bcc, ddd, zzz. 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:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜