I want to remove double quotes from a String

ankur picture ankur · Oct 3, 2013 · Viewed 400.8k times · Source

I want to remove the "" around a String.

e.g. if the String is: "I am here" then I want to output only I am here.

Answer

Elias Van Ootegem picture Elias Van Ootegem · Oct 3, 2013

Assuming:

var someStr = 'He said "Hello, my name is Foo"';
console.log(someStr.replace(/['"]+/g, ''));

That should do the trick... (if your goal is to replace all double quotes).

Here's how it works:

  • ['"] is a character class, matches both single and double quotes. you can replace this with " to only match double quotes.
  • +: one or more quotes, chars, as defined by the preceding char-class (optional)
  • g: the global flag. This tells JS to apply the regex to the entire string. If you omit this, you'll only replace a single char.

If you're trying to remove the quotes around a given string (ie in pairs), things get a bit trickier. You'll have to use lookaround assertions:

var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"([^"]+(?="))"/g, '$1'));
//logs remove foo delimiting quotes
str = 'remove only "foo" delimiting "';//note trailing " at the end
console.log(str.replace(/"([^"]+(?="))"/g, '$1'));
//logs remove only foo delimiting "<-- trailing double quote is not removed

Regex explained:

  • ": literal, matches any literal "
  • (: begin capturing group. Whatever is between the parentheses (()) will be captured, and can be used in the replacement value.
  • [^"]+: Character class, matches all chars, except " 1 or more times
  • (?="): zero-width (as in not captured) positive lookahead assertion. The previous match will only be valid if it's followed by a " literal
  • ): end capturing group, we've captured everything in between the opening closing "
  • ": another literal, cf list item one

The replacement is '$1', this is a back-reference to the first captured group, being [^" ]+, or everyting in between the double quotes. The pattern matches both the quotes and what's inbetween them, but replaces it only with what's in between the quotes, thus effectively removing them.
What it does is some "string with" quotes -> replaces "string with" with -> string with. Quotes gone, job done.

If the quotes are always going to be at the begining and end of the string, then you could use this:

str.replace(/^"(.+(?="$))"$/, '$1');

or this for double and single quotes:

str.replace(/^["'](.+(?=["']$))["']$/, '$1');

With input remove "foo" delimiting ", the output will remain unchanged, but change the input string to "remove "foo" delimiting quotes", and you'll end up with remove "foo" delimiting quotes as output.

Explanation:

  • ^": matches the beginning of the string ^ and a ". If the string does not start with a ", the expression already fails here, and nothing is replaced.
  • (.+(?="$)): matches (and captures) everything, including double quotes one or more times, provided the positive lookahead is true
  • (?="$): the positive lookahead is much the same as above, only it specifies that the " must be the end of the string ($ === end)
  • "$: matches that ending quote, but does not capture it

The replacement is done in the same way as before: we replace the match (which includes the opening and closing quotes), with everything that was inside them.
You may have noticed I've omitted the g flag (for global BTW), because since we're processing the entire string, this expression only applies once.
An easier regex that does, pretty much, the same thing (there are internal difference of how the regex is compiled/applied) would be:

someStr.replace(/^"(.+)"$/,'$1');

As before ^" and "$ match the delimiting quotes at the start and end of a string, and the (.+) matches everything in between, and captures it. I've tried this regex, along side the one above (with lookahead assertion) and, admittedly, to my surprize found this one to be slightly slower. My guess would be that the lookaround assertion causes the previous expression to fail as soon as the engine determines there is no " at the end of the string. Ah well, but if this is what you want/need, please do read on:

However, in this last case, it's far safer, faster, more maintainable and just better to do this:

if (str.charAt(0) === '"' && str.charAt(str.length -1) === '"')
{
    console.log(str.substr(1,str.length -2));
}

Here, I'm checking if the first and last char in the string are double quotes. If they are, I'm using substr to cut off those first and last chars. Strings are zero-indexed, so the last char is the charAt(str.length -1). substr expects 2 arguments, where the first is the offset from which the substring starts, the second is its length. Since we don't want the last char, anymore than we want the first, that length is str.length - 2. Easy-peazy.

Tips:

More on lookaround assertions can be found here
Regex's are very useful (and IMO fun), can be a bit baffeling at first. Here's some more details, and links to resources on the matter.
If you're not very comfortable using regex's just yet, you might want to consider using:

var noQuotes = someStr.split('"').join('');

If there's a lot of quotes in the string, this might even be faster than using regex