How to Replace Single with Double quotes in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Replace Single with Double quotes #

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

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

We pass the following parameters to the String.replaceAll method:

  1. a substring to match in the string. In this scenario, we match all single quotes in the string.
  2. a replacement for each match. We replace each single quote with a double quote.
We have to alternate the strings, which makes the replaceAll method very hard to read.

I prefer using backticks to wrap the strings. The following code achieves the same goal.

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

Instead of alternating single and double quotes, we used backticks when passing parameters to the replaceAll method.

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 single with double quotes, e.g. const replaced = str.replace(/'/g, ");. The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.

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

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

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 single quote in the string, and not just the first occurrence.

We used a double quote for the replacement string.

If you get stuck reading a regular expression, check out this regex cheatsheet by MDN.

Which approach you pick is a matter of personal preference. I'd go with the replaceAll method to avoid using regular expressions.

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.