Getting Unterminated String Literal Error When Using Newlines In JavaScript Variable

Nothing like a good Unterminated String Literal Error to fog up your day huh? Well I found a neat little trick to squash this nasty bug with JavaScript today!

The Problem

The problem in my case is that I wanted to place the contents of a PHP variable, filled with data from a database table, into a JavaScript variable which I thought could be easily done like in  the following JavaScript code example:

var sc = “<?php echo $email_content; ?>”;

WRONG! I discovered that when the PHP variable holds text with newline characters in it, like you’ll often encounter when retrieving data from a database or from a textarea, or even a file, JavaScript throws the nasty old “Unterminated string literal” error! I’ve learned to hate this general JavaScript error over the years, but today, I stumbled upon a small, yet useful, trick that makes this error go away in cases like this.

The Solution:

Believe it or not, the solution is as simply as replacing quotes in the JavaScript code with backticks. If you don’t know what a backtick is, read on, otherwise your JavaScript code should look like this after replacing quotes with backticks:

var sc = `<?php echo $email_content; ?>`;

What is a Backtick?

A backtick is the little character that looks like a slanted single quotation mark that normally calls the key above the tab key home on a normal English keyboard. Otherwise known as the Marigold key, grave accent or backquote, the character is a tricky one simply because no one knows what to call it. However, in the land of computer programming, it is commonly referred to as the backtick character, so that’s what we’ll call it. Cool? Okay!


Leave a Reply

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