Borislav Hadzhiev
Thu Oct 14 2021·3 min read
Photo by Nitish Meena
To replace double with single quotes in a string:
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.replaceAll
method returns a new string with all matches replaced.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:
\
to escape them.Alternatively, you could use backticks
, if you find that more readable.
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.
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:
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.replace
method will return a new string with all matches replaced.// 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.
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.