Yongju Lee
Yongju Lee

Reputation: 251

How to set up a javascript variable with apostrophes and quotations marks (Can't escape it!)

I am currently working on a project where I don't have an access to their server side. All I can do is retrieve the blog data from their template editor, but it seems like there's no way to escape HTML using their template syntax. This is bad, but I need to assign the HTML in a javascript variable to create a Json data.

In Python, you'd use both apostrophes and quotation marks without escaping it by using three apostrophes as such:

example = ''' 
            this '/ is great! ""Wahjhahaha
          '''

Is there any equivalent way of this in Javascript? As I mentioned, I can't escape the HTML data.

Upvotes: 1

Views: 1863

Answers (2)

Krzysztof Janiszewski
Krzysztof Janiszewski

Reputation: 3854

There are several approches depending on what you want to do.

You can use single quoute inside double quote.

You can use double quote inside single quote.

And if you want to use double quote inside double quote you have to use backslash (\) before the element. The same applies for single quote

console.log('This is double quote inside single quote "');
console.log("This is single quote inside double quote '");
console.log('This is single quote inside single quote \'');
console.log("This is double quote inside double quote \"");
console.log('\' " " \'');
console.log("' \" \" '");

EDIT

You need to use function replace()

var str = "Using single quotes ' ' sdsd 'sd 'dssd sdf' 'sdf'";
str = str.replace(/'/g, "\\'");
console.log(str);

Similarly you can do with double quotes.

Alternatively you can use backticks, but I would not recommend it (backticks in IE11)

console.log(`Here you can use both ' single and " double quotes without backslashes`);

Upvotes: 0

Ramesh
Ramesh

Reputation: 13266

"\" is the escape character in javascript.

var example = "This is a string with \' \" ";
console.log(example);

Upvotes: 1

Related Questions