Quotes Within Quotes Within Quotes in JavaScript

There’s a way to nest string in two or more quotes in JavaScript, and you will love the simplicity of it.

Published Categorized as JavaScript, Web & Code

I’m creating a popup form for one of my products, and I’m doing it by writing HTML elements directly into the DOM with a <script> element in JavaScript:

  document.querySelector('.wrapper').insertAdjacentHTML('afterend', '<div id="floating-cta"><a href="#order-form">Buy Now</a></div>');

To the <a> element in my insertAdjacentHTML statement, I wanted to add an onclick=() attribute to push the following custom event to a dataLayer object for analytics purposes:

onclick="dataLayer.push({ 'event' : 'click-floating-cta' });"

But here’s the thing…

The Problem

I was already using single quotes for my script and double quotes for the HTML element I wanted my script to insert into the document.

So using either single or double quotes would have broken my function halfway and prevented it from working, as JavaScript would have misunderstood what I wanted it to do.

This, as you can see by the broken syntax highlighter below, wouldn’t work:

  document.querySelector('.wrapper').insertAdjacentHTML('afterend', '<div id="floating-cta"><a href="#order-form" onclick="dataLayer.push({'event' : 'click-floating-cta'});">Buy Now</a></div>');

And neither would this:

  document.querySelector('.wrapper').insertAdjacentHTML('afterend', '<div id="floating-cta"><a href="#order-form" onclick="dataLayer.push({"event" : "click-floating-cta"});">Buy Now</a></div>');

So I found myself wondering, how do you add quotes without quotes within quotes in JavaScript?

I’m happy to report I’ve found the solution, and I’m about to share it with you all below.

The Solution

The solution, as it turns out, is to use \" instead of " and \' instead of ' within your string.

To add quotes within quotes within quotes in JavaScript, prepend each single or double quote with the backslash escape character (respectively, \' and \").

With the above, I modified my code to this, and it worked beautifully:

  document.querySelector('.wrapper').insertAdjacentHTML('afterend', '<div id="floating-cta"><a href="#order-form" onclick="dataLayer.push({\'event\' : \'click-floating-cta\'});">Buy Now</a></div>');

As you can tell by the colors of the code above, the syntax highlighter also agrees with me.

In Conclusion

The backslash escape, as its name implies, is used to escape special characters on the screen. It is a great workaround for when you need to nest multiple quoted statements together or when you want to use the same style of quotes within quotes.

Image courtesy of KrakenImages.com /Depositphotos

Leave a comment

Your email address will not be published. Required fields are marked *