Suppose you have a string with single or double quotation marks in JavaScript. And, for one reason or another, you want to remove those quotation marks from your string.
What’s the best way to accomplish this?
To remove quotation marks from a string in JavaScript, use the 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:
String.replace(pattern, replacement);
As you can see from the code above, the String.replace() method lets you replace a pattern
with a replacement
, where:
- The
pattern
is either a string or RegEx; - The
replacement
is 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 assume that, in our JavaScript app, there’s a string named myString
.
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 String.replace()
function.
// 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, ''));
Notice the 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.