user8822553
user8822553

Reputation:

How to do a single quote inside of a double quote inside a single quote?

I have a simple piece of html code like this:

<button onclick = 'getAnsVoc("J'ai attendu mon ami.", "Q2A", "Q2B", "Q2C", "Q2D")'>Answer</button>

It is super simple but I have no idea how to make the expression valid while still being able to have the apostrophe in the code. I did not know how to phrase it so I came here for answers.

Upvotes: 0

Views: 45

Answers (1)

Martin
Martin

Reputation: 22770

You need to escape the character (') that is the same character as the "wrapper" ('). You usually do this with a preceeding slash : \'.

Therefore:

<button onclick='getAnsVoc("J\'ai attendu mon ami.", "Q2A", 
                "Q2B", "Q2C", "Q2D")'>Answer</button>

As an alterative you can also replace the character with it's HTML entity name. For ' you can use &#39;. Therefore:

<button onclick='getAnsVoc("J&#39;ai attendu mon ami.", "Q2A", 
                "Q2B", "Q2C", "Q2D")'>Answer</button>

If you are playing with user submitted (or otherwise dynamic) data and you need to ensure that single (') and double (") quotes are correctly encoded to be "safe" in javascript then you need a function to "encode" these elements.

An example of this sort of functionality is at the bottom of the links list below:


Useful links:

Upvotes: 2

Related Questions