Borislav Hadzhiev
Thu Oct 14 2021·3 min read
Photo by Andrew Neel
To remove all double quotes from a string call the replaceAll()
method on
the string, passing it string containing a double quote as the first parameter
and an empty string as the second. The replaceAll
method will return a new
string with all double quotes removed.
const str = 'hel"l"o wor"l"d'; const removed = str.replaceAll('"', ''); console.log(removed); // 👉️ hello world
We passed the following parameters to the String.replaceAll method:
The replaceAll
method does not change 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 need to support the browser use the replace
method instead.To remove double quotes from a string:
replace()
method on the string, passing it a regular expression
that matches all double quotes as the first parameter and an empty string as
the second.replace
method will return a new string with all double quotes removed.// Supported in IE const str = 'hel"l"o wor"l"d'; const removed = str.replace(/"/g, ''); console.log(removed); // 👉️ hello world
The first parameter we passed to the String.replace method is a regular expression we want to match in the string.
The two forward slashes / /
mark the beginning and end of the regular
expression.
g
(global) flag because we want to match all occurrences of a double quote in the string and not just the first occurrence.If you ever need help reading a regular expression, check out this regex cheatsheet by MDN. It's by far the best one out there.
The second parameter we pass to the replace
method is an empty string because
we want to remove all double quotes from the string.
The replace
method doesn't mutate the original string, it returns a new
string.
To remove double quotes from a string:
split()
method, passing it a string containing a double quote to
get an array of substrings.join()
method on the array passing it an empty string as a
parameter to join the array elements into a string.const str = 'hel"l"o wor"l"d'; const removed = str.split('"').join(''); console.log(removed); // 👉️ hello world
The String.split method splits the string into an array of substrings based on a provided separator.
const str = 'hel"l"o wor"l"d'; const split = str.split('"'); // 👉️ ['hel', 'l', 'o wer', 'l', 'd'] console.log(split);
The final step is to concatenate the array elements into a string using the Array.join method.
My preferred approach is to use the replaceAll
method when I can, however if
you have to support Internet Explorer use either of the other approaches.