views:

43

answers:

3

I understand escaping quotes etc. for javascript. Are there any other characters that can be used to encase the whole thing rather than just " or '? Both characters will come up in my piece of text and I don't want to have to put a / before each instance

So, instead of:

("Some text where he said "I like this, she say's")

something like this(although I'm not expecting the percentage sign to be used)

(%Some text where he said "I like this, she say's%

Hope that makes a bit of sense! Thank you.

A: 

No. Only " and ' are valid string delimiters. You have to escape them either as

"...\"...'...";
'..."...\'...';

(As a cheat, you can put the string in a hidden <div> and read the textContent in JS.)

(As another cheat, /Some text where he said "I like this, she say's/.source.)

KennyTM
Oooh, I like that second cheat. Thanks!
James Wanchai
For the first cheat, however, you'd need to HTML-escape the string first.
Pointy
The second one didn't seem to work unless I'm doing something stupid?!
James Wanchai
@James: Hmm, works on Safari.
KennyTM
Hmmm...OK, got to go out now for a bit, but will have a go again later this afternoon. It was probably me doing something wrong! Thank you!
James Wanchai
No, still can't get it to work. How does it know that the slashes at the beginning and the end are the ones to take regard of rather than the other ones in the html? Thanks.
James Wanchai
@James: The 1st and 2nd "cheat" are mutually exclusive. Use the 2nd like `var xyz = /blah "blah" 'blah'/.source;`. Not that I recommend it.
KennyTM
Nope, still can't get it to work, which is annoying. Oh well!
James Wanchai
+1  A: 

Literal strings need to be declared with either " or '. And within such a declaration, the quotes that surround the string value need to be escaped. So:

"Some text where he said \"I like this, she say's"
'Some text where he said "I like this, she say\'s'

Both will be interpreted as:

Some text where he said "I like this, she say's
Gumbo
It's OK to always escape either quote, regardless of the quotes used to surround the string constant. That makes the writing of server-side "escapeJS" functions a little easier.
Pointy
A: 

If you're working with content that comes from your server-side template language, you may also have to worry about encoding multi-byte sequences and "control" characters.

Pointy