gautam
gautam

Reputation: 11

Using escape function throws js error because special characters are present in text

the sample is like this:-

var encdata= escape('They're good at coding."Super". Its great!');

Now the error comes because it finds the closing apostrophe at they're instead at last.

It will work if i code the same as

var encdata= escape('They re good at coding."Super".Its great!');

Similarly if i use double quotes and give like

var encdata= escape("They're good at coding."Super".Its great!");

It will throw error at "super" but not at they're.

So, it should work when my text contains both double quotes and apostrophe.

And i can't wrap my text within as 'text' or "text".

So, i need an alternate solution for it

Upvotes: 1

Views: 406

Answers (3)

helloandre
helloandre

Reputation: 10721

you have to use a slash \ to escape the apostrophe inside the single quotes, or alternatively the open quotes inside the double quotes.

'They\'re good at coding."Super". Its great!'
"They're good at coding.\"Super\".Its great!"

This is true for almost every language ever. Adding a slash to characters lets it know that you want it to be a literal character instead of having a special meaning.

Upvotes: 0

voigtan
voigtan

Reputation: 9031

you need to use \" or \':

var encdata= escape("They're good at coding.\"Super\".Its great!");

or

var encdata= escape('They\'re good at coding."Super".Its great!');

Upvotes: 0

Alex K.
Alex K.

Reputation: 175766

Escape the characters with \' or \";

var encdata = escape('They\'re good at coding."Super".Its great!');
var encdata = escape("They're good at coding.\"Super\".Its great!");

Upvotes: 1

Related Questions