Back to JavaScript
2025-11-278 min read

SyntaxError: string literal contains an unescaped line break (JavaScript)

Learn SyntaxError: string literal contains an unescaped line break (JavaScript) step by step with clear examples and exercises.

Title: SyntaxError: string literal contains an unescaped line break (JavaScript)

Why This Matters

In JavaScript, a SyntaxError occurs when the code you write is not valid according to the language's syntax rules. One such error is the "string literal contains an unescaped line break." Understanding how to handle string literals properly will help you avoid this and other common JavaScript errors. This lesson will explain why this matters, provide prerequisites, delve into the core concept, offer a worked example, discuss common mistakes, and propose practice questions.

Prerequisites

Before diving into the core concept, make sure you have a good grasp of the following topics:

  1. Basic JavaScript syntax (variables, data types, operators)
  2. Strings in JavaScript (creating strings, concatenation, and manipulation)
  3. Escape characters in JavaScript (\n, \t, \\, etc.)
  4. Control structures such as loops and conditional statements
  5. File I/O operations (reading files)
  6. Regular expressions (optional but helpful for understanding some of the common mistakes)

Core Concept

A string literal is a sequence of zero or more characters enclosed within single quotes (') or double quotes ("). In JavaScript, strings can span multiple lines if they are not terminated correctly. This can lead to the "string literal contains an unescaped line break" error.

To avoid this error, you should either:

  1. Use a single quote for the entire string and escape any single quotes within it using a backslash (\'). For example:
let myString = 'This is a "quoted" string';
  1. Use double quotes for the entire string and escape any double quotes within it using a backslash (\"). For example:
let myString = "This is a 'quoted' string";
  1. If your string spans multiple lines, you can use a backslash followed by n to create a new line within the string. However, be careful not to have two consecutive newline characters (\n\n) or you will still encounter the error. For example:
let myLongString = 'This is\na multi-line\nstring';

String Escaping

In JavaScript, escape characters are used to represent special characters within a string. The most common escape characters are \n (newline), \t (tab), and \\ (backslash).

For example:

let myString = 'This is a new line\nand another one';

Multiline Strings with Template Literals

Starting from ECMAScript 6, you can use template literals to create multiline strings more easily. Template literals are enclosed in backticks (` `). To include a newline within the string, simply write it as is:

let myLongString = `This is
a multi-line
string`;

Escape Character Table

Here's a table summarizing some common escape characters in JavaScript:

| Character | Represents | Example |

|-----------|------------------------------|------------------------|

| \n | Newline (line break) | \n or \r\n |

| \t | Tab | \t |

| \\ | Backslash | \\ |

| \' | Single quote | \' |

| \" | Double quote | \" |

| \b | Backspace | \b |

| \f | Form feed | \f |

| \r | Carriage return | \r or \r\n |

| \v | Vertical tab | \v |

Worked Example

Let's explore a real-world scenario where this error might occur and learn how to fix it.

Suppose you are writing a JavaScript program that reads a file containing multiple lines of data, each line representing a user’s name. To store the names in an array, you might initially write something like this:

let users = [];

// Read file and store contents in a variable
let data = readFile('users.txt');

// Split the data into individual lines and store in users array
for (let line of data.split('\n')) {
users.push(line);
}

However, if the users.txt file contains a user name with a line break (e.g., "John\nDoe"), the loop will attempt to push an unescaped line break into the users array, causing a SyntaxError. To fix this, you can modify the loop as follows:

let users = [];

// Read file and store contents in a variable
let data = readFile('users.txt');

// Split the data into individual lines, trim any leading/trailing whitespace, and store in users array
for (let line of data.split('\n').map(line => line.trim())) {
users.push(line);
}

Now, when you encounter a user name with a line break, the trim() function will remove it before adding the name to the users array.

Common Mistakes

  1. Not escaping single quotes within a string using a backslash (e.g., let myString = 'O\'Connor').
  2. Using two consecutive newline characters in a string (e.g., let myLongString = "This is\n\nnew multi-line\nstring").
  3. Not trimming leading or trailing whitespace from a multiline string before adding it to an array (e.g., the loop from the worked example without the map() and trim() calls).
  4. Using triple quotes (` `) for multiline strings instead of backticks, which are not supported in JavaScript as of ECMAScript 6.
  5. Forgetting to escape special characters within a string, such as backslashes or tabs.
  6. Assuming that the split() method automatically trims whitespace from each line (it does not).
  7. Not accounting for the possibility of trailing newlines in the input file, which can cause extra empty elements in the resulting array.

Common Mistakes - Examples

  1. Incorrectly escaping single quotes:
let myString = 'O'Connor'; // SyntaxError: Unexpected identifier
  1. Using two consecutive newline characters:
let myLongString = "This is\n\nnew multi-line\nstring"; // SyntaxError: string literal contains an unescaped line break
  1. Not trimming leading or trailing whitespace from a multiline string:
let users = [];

// Read file and store contents in a variable
let data = readFile('users.txt');

// Split the data into individual lines and store in users array (without trim())
for (let line of data.split('\n')) {
users.push(line);
}
  1. Using triple quotes instead of backticks:
let myLongString = """This is
a multi-line
string"""; // SyntaxError: Unexpected token (expected punch)
  1. Forgetting to escape special characters:
let myString = 'C:\Users\John'; // SyntaxError: Invalid or unexpected token
  1. Assuming that the split() method automatically trims whitespace from each line:
let users = [];

// Read file and store contents in a variable
let data = readFile('users.txt');

// Split the data into individual lines (without trim())
for (let line of data.split('\n')) {
users.push(line);
}
  1. Not accounting for trailing newlines:
let users = [];

// Read file and store contents in a variable
let data = readFile('users.txt');

// Split the data into individual lines, trim any leading/trailing whitespace, and store in users array
for (let line of data.split('\n').map(line => line.trim())) {
users.push(line);
}

// Assume there are no trailing newlines
console.log(users[users.length - 1]); // Outputs an empty string if the file has a trailing newline

Practice Questions

  1. Given the following code:
let myString = "This is a 'quoted' string with a single quote";
console.log(myString);

What will be printed to the console, and why?

  1. Suppose you have a JavaScript program that reads a file containing user names separated by commas and line breaks (e.g., "Alice\nBob, Charlie\nDave"). How would you store these names in an array without encountering any errors due to unescaped line breaks or commas?
  1. You are writing a JavaScript program that reads a file containing JSON data. The JSON data includes strings with backslashes (e.g., "C:\\Users\\John"). How would you parse this JSON data correctly without encountering any errors due to unescaped backslashes?
  1. Given the following code:
let myString = 'This is a \'quoted\' string with an escaped single quote';
console.log(myString);

What will be printed to the console, and why?

  1. You are writing a JavaScript program that reads a file containing user names separated by spaces and line breaks (e.g., "Alice Bob Charlie Dave"). How would you store these names in an array without encountering any errors due to unescaped spaces or line breaks?

FAQ

  1. Why can't I just use triple quotes (""") for multiline strings in JavaScript?

Triple quotes are not supported in JavaScript as of ECMAScript 6. However, they are part of the ECMAScript Stage 3 Proposals and may be added to future versions of the language.

  1. What happens if I forget to escape a single quote within a string using a backslash?

If you do not escape a single quote within a string, JavaScript will interpret it as the end of the string. For example:

let myString = 'O'Connor'; // SyntaxError: Unexpected identifier
  1. What is the difference between a backslash (\) and two backslashes (\\) in JavaScript strings?

A single backslash (\) is used as an escape character, while two consecutive backslashes (\\) represent a single backslash within a string. For example:

let myString = 'C:\Users'; // This is a valid path with a single backslash
let myEscapedString = 'C:\\Users'; // This is also a valid path, but the second backslash is escaped within the string
  1. What should I do if I encounter an unescaped line break in a multiline string?

To avoid the "string literal contains an unescaped line break" error, ensure that you either escape newlines using a backslash (\n) or use template literals with backticks (` `).

  1. How can I handle strings containing special characters such as backslashes or tabs in JavaScript?

To include special characters within strings, you should escape them using the appropriate escape character (e.g., \n for newline, \t for tab, and \\ for backslash). For example:

let myString = 'C:\Users\John'; // This is a valid string with escaped backslashes
  1. Why does the split() method not automatically trim whitespace from each line?

The split() method in JavaScript splits a string into an array of substrings based on a specified separator (in this case, newlines). It does not remove any leading or trailing whitespace by default. To achieve that, you can use the map() and trim() methods as shown in the worked example.

  1. How can I account for trailing newlines when reading a file?

To handle trailing newlines when reading a file, you can read the entire contents of the file into a single string, then split it using the split('\n') method. This will include any trailing newline as the last element in the resulting array. To remove the trailing newline if necessary, you can use the pop() method to remove the last element from the array. For example:

let users = [];

// Read file and store contents in a variable
let data = readFile('users.txt');

// Split the data into individual lines, trim any leading/trailing whitespace, and
SyntaxError: string literal contains an unescaped line break (JavaScript) | JavaScript | XQA Learn