How to Replace Double with Single Quotes in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 14 20212 min read

banner

Photo by Nitish Meena

Replace Double with Single Quotes in Strings #

To replace double with single quotes in a string:

  1. Call the replaceAll() method on the string, passing it a string containing a double quote as the first parameter and a string containing a single quote as the second.
  2. The replaceAll method returns a new string with all matches replaced.
index.js
const str = 'He said: "test 123"'; const replaced = str.replaceAll('"', "'"); console.log(replaced); // ๐Ÿ‘‰๏ธ "He said: 'test 123'"

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

  1. a substring to match in the string. In our case we want to match all double quotes in the string.
  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 could 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'"

In the code snippet we use backticks to wrap the parameters we pass to the replaceAll method. This achieves the same result as alternating single and double quotes.

Note that 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 double with single quotes in a string:

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

The first parameter we pass to the String.replace method is a regular expression where we match all double 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 double quote in the string, and not just the first occurrence.

We provide a single quote as a replacement for each match.

If you ever need help reading a regular expression, check out this regex cheatsheet by MDN. It's definitely the best one out there.

Using the replaceAll method is definitely more straight forward and readable, however if you have to support Internet Explorer, the replace method approach gets the job done.

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