Someone
Someone

Reputation: 10575

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 valid. Here $('#txt1').attr('value') is a dynamic value. It may have abc, bcc, ddd, zzz. How can I do this?

Upvotes: 7

Views: 28691

Answers (4)

Stephen
Stephen

Reputation: 18964

It is close. Use the .val() method:

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

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816242

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 '\''.

Upvotes: 13

C. Spencer Beggs
C. Spencer Beggs

Reputation: 529

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

Upvotes: 5

amit_g
amit_g

Reputation: 31250

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

Upvotes: 0

Related Questions