How to Replace Single with Double quotes in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 14 20212 min read

banner

Photo by Eepeng Cheong

Replace Single with Double quotes #

To replace single with double quotes in a string:

  1. Call the replaceAll() method on the string, passing it a string containing a single quote as the first parameter and a string containing a double quote as the second.
  2. The replaceAll method returns a new string with all matches replaced.
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"'

In the code snippet, instead of alternating single and double quotes, we use backticks when passing parameters to the replaceAll method.

The replaceAll method does not change the contents of the original string, it returns a new string with all matches replaced. Strings are immutable in JavaScript.

The replaceAll method is not supported by Internet Explorer. If you have to support the browser, use the replace method instead.

To replace single with double quotes in a string:

  1. Call the replaceAll() method on the string, passing it a regular expression that matches all single quotes as the first parameter and a string containing a double quote as the second.
  2. The replace method will return a new string with all matches replaced.
index.js
// Supported in IE const str = "They said: 'test 123'"; const replaced = str.replace(/'/g, `"`); console.log(replaced); // ๐Ÿ‘‰๏ธ 'They said: "test 123"'

The first parameter we pass to the String.replace method is a regular expression where we match all single quotes.

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

We use 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 provide a double quote as a replacement for each match.

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

Using the replaceAll method is my preferred approach whenever possible, however if you have to support Internet Explorer, you can use thereplace method.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee