How to Replace Double with Single Quotes in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Replace Double with Single Quotes in Strings #

Use the String.replaceAll() method to replace double with single quotes, e.g. const replaced = str.replaceAll('"', "'");. The replaceAll method will return a new string where all occurrences of double quotes are replaced with single quotes.

index.js
const str = 'He said: "test 123"'; const replaced = str.replaceAll('"', "'"); console.log(replaced); // 👉️ "He said: 'test 123'"

We passed the following arguments to the String.replaceAll method:

  1. a substring to match in the string. (we match all double quotes)
  2. a replacement for each match. (we replace each double quote with a single) quote.
Notice how we alternate the quotes to not have to use a backslash \ to escape them.

Alternatively, you can use backticks, if you find that more readable.

index.js
const str = 'He said: "test 123"'; const replaced = str.replaceAll(`"`, `'`); console.log(replaced); // 👉️ "He said: 'test 123'"

We used backticks to wrap the parameters we passed to the replaceAll method. This achieves the same result as alternating single and double quotes.

Note that the replaceAll method doesn't change the contents of the original string, it returns a new string with all matches replaced. Strings are immutable in JavaScript.

Alternatively, you can use the replace() method.

Use the String.replace() method to replace double with single quotes, e.g. const replaced = str.replace(/"/g, "'");. The replace method will return a new string where all occurrences of double quotes are replaced with single quotes.

index.js
const str = 'He said: "test 123"'; const replaced = str.replace(/"/g, "'"); console.log(replaced); // 👉️ "He said: 'test 123'"

The first parameter we passed to the String.replace method is a regular expression that matches all double quotes.

The forward slashes / / mark the beginning and end of the regular expression.

We used the g (global) flag because we want to match all occurrences of a double quote in the string, and not just the first occurrence.

We provided a single quote as the replacement for each match.

If you ever need help reading a regular expression, check out this regex cheatsheet by MDN.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.