What’s the best way to accomplish this?
String.replace() method. You can target the quotation marks with RegEx and replace them with a null value.
The syntax for the
String.replace() method is as follows:
As you can see from the code above, the String.replace() method lets you replace a
pattern with a
patternis either a string or RegEx;
replacementis either another string or a function to be called for each match.
It’s compatible with all modern and legacy web browsers, including Internet Explorer 6+, Microsoft Edge 12+, and Safari 3.1+. So compatibility, even for users with dated software, won’t be an issue.
How It Works
Let’s also assume that, in
myString, we’ve stored the following quote from The Little Prince by Antoine de Saint-Exupéry:
// Store quote in string let myString = '"One only understands the things that one tames," said the fox.'
To remove the double quotation marks (“”) from
myString, we will use the
// Store quote in string let myString = '"One only understands the things that one tames," said the fox.' // Remove double quotation marks from string console.log(myString.replace(/["]/g, ''));
g at the end of our regular expression. It stands for
global, and it makes the pattern applicable to all instances of the quotation symbol, not just the first one. (Without it, only the first quotes will get removed.)
The output is a string with successfully removed double quotes:
One only understands the things that one tames, said the fox.
Give the code snippet above a try. Open up your browser’s development tools right now and copy/paste this into the console.
The Best Solution
When having to remove quotation marks from a string, you can come across four kinds of them. There are single straight, double straight, single curly, and double curly quotation marks.
Matters are complicated further by the fact that single and double curly quotation marks can be opening (tilted forward) or closing (tilted backward).
If, at any given moment of time, you can’t be sure what kinds of quotation marks your string can have, your best bet is to write RegEx that covers all of them.
// Store quote in string let myString = '“One only understands the things that one tames,“ said the fox.' // Remove single, double, or curly quotation marks from string console.log(myString.replace(/['‘’"“”]/g, ''));
This makes the regular expression longer and thus less performant. However, it makes it universally effective at removing quotation marks, no matter the symbol.
Good programming, at the end of the day, is all about trade-offs.