1

I have the following string:

'You've just created'

When I assign this string to a JavaScript variable, this is interpreted as 2 strings because there's a ' character.

How can I escape it?

3
  • 1
    When you say ‘pass it to a variable’, what do you mean? Are you simply defining a static variable, or using server-side code to generate JavaScript code with the variable in it? If the latter, you should look at using a JSON encoder to create your JavaScript literals. Commented Oct 28, 2010 at 12:23
  • @bobince: hmm... I assumed the former when tidying up the question grammar, but now that you mention it, the issue could be the result of outputting unescaped strings from the server. Commented Oct 28, 2010 at 12:24
  • mothereff.in/js-escapes#1You%27ve%20just%20created Commented Feb 16, 2012 at 11:42

2 Answers 2

2

In JS code blocks, use a backslash:

var text = 'You \'ve just created'

in JS inside HTML, use a HTML entity:

<a onclick='alert("You &apos;ve just created");'>
Sign up to request clarification or add additional context in comments.

Comments

2

You can use either " or ' to quote a string, so you could do it this way:

"You've just created"

or you can use a \ to quote just one character:

'You\'ve just created'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.