373

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.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
ankur
  • 3,951
  • 4
  • 16
  • 7

18 Answers18

573

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

Sølve T.
  • 4,159
  • 1
  • 20
  • 31
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • 2
    @rid: I edited, expainding a bit on what the expression does, and how to customize it – Elias Van Ootegem Oct 03 '13 at 10:02
  • 1
    I think `someStr.replace(/^"(.+)"$/,'$1');` should use `.*` instead of `.+`. Test case `'""'`. For example `'""'.replace(/^"(.+)"$/,'$1')` return `""`, but `'""'.replace(/^"(.*)"$/,'$1')` returns `` – Islam Azab Jan 25 '21 at 14:44
  • wouldnt `str.length -2` cut off the last character? – MoralCode May 09 '23 at 21:20
  • @MoralCode No, seeing as you're taking the substring starting at index 1 (of a zero-indexed string) and you want to exclude the last character, too. So `str.length` is the full length including the first and last character. The substring you're after starts at index 1, and has a total length of the original string -2. You can try with `x = "'remove single quotes'"; x.substr(1, x.length-2)`. Works like a charm – Elias Van Ootegem May 15 '23 at 17:28
131
str = str.replace(/^"(.*)"$/, '$1');

This regexp will only remove the quotes if they are the first and last characters of the string. F.ex:

"I am here"  => I am here (replaced)
I "am" here  => I "am" here (untouched)
I am here"   => I am here" (untouched)
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
112

If the string is guaranteed to have one quote (or any other single character) at beginning and end which you'd like to remove:

str = str.slice(1, -1);

slice has much less overhead than a regular expression.

darrinm
  • 9,117
  • 5
  • 34
  • 34
  • 3
    Surprised this has been downvoted since it's exactly the kind of 'quick' operation you need if you're dealing with RDF literals (in N3, for example, URIs are usually denoted like `` and literals like `"literal"`). So here's an upvote. ;) – Mark Birbeck Mar 20 '18 at 10:23
  • 4
    (Particularly because the original question says they want to remove the quotes *around* a string.) – Mark Birbeck Mar 20 '18 at 10:25
  • It removes "" but also removes the characters from the both the ends – Harshit Aug 20 '21 at 00:21
  • @Harshit It removes 1 character from each end. That is all. It doesn't matter what the characters are but for this question it is assumed that they are quotes. – darrinm Jan 09 '22 at 23:45
56

If you have control over your data and you know your double quotes surround the string (so do not appear inside string) and the string is an integer ... say with :

"20151212211647278"

or similar this nicely removes the surrounding quotes

JSON.parse("20151212211647278");

Not a universal answer however slick for niche needs

Scott Stensland
  • 26,870
  • 12
  • 93
  • 104
20

If you only want to remove the boundary quotes:

function stripquotes(a) {
    if (a.charAt(0) === '"' && a.charAt(a.length-1) === '"') {
        return a.substr(1, a.length-2);
    }
    return a;
}

This approach won't touch the string if it doesn't look like "text in quotes".

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
Kos
  • 70,399
  • 25
  • 169
  • 233
15

A one liner for the lazy people

var str = '"a string"';
str = str.replace(/^"|"$/g, '');
Kellen Stuart
  • 7,775
  • 7
  • 59
  • 82
  • This is the most appropriate answer. `/"/g` won't work for `"My name is \"Jason\""`. – Jason Liu Nov 16 '18 at 22:02
  • 1
    this answer removes *every* quote in the beginning and the end, which is not good in case of `" - is a quote` string, so it's not the same as *around* – vladkras Sep 23 '19 at 07:37
11

If you only want to remove quotes from the beginning or the end, use the following regular expression:

'"Hello"'.replace(/(^"|"$)/g, '');
Denis
  • 5,061
  • 1
  • 20
  • 22
5

To restate your problem in a way that's easier to express as a regular expression:

Get the substring of characters that is contained between zero or one leading double-quotes and zero or one trailing double-quotes.

Here's the regexp that does that:

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

Breaking down the regexp:

  • ^"? a greedy match for zero or one leading double-quotes
  • "?$ a greedy match for zero or one trailing double-quotes
  • those two bookend a non-greedy capture of all other characters, (.+?), which will contain the target as $1.

This will return delimited "string" here for:

str = "delimited "string" here"  // ...
str = '"delimited "string" here"' // ...
str = 'delimited "string" here"' // ... and
str = '"delimited "string" here'
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
2

If you want to remove all double quotes in string, use

var str = '"some "quoted" string"';
console.log( str.replace(/"/g, '') );
// some quoted string

Otherwise you want to remove only quotes around the string, use:

var str = '"some "quoted" string"';
console.log( clean = str.replace(/^"|"$/g, '') );
// some "quoted" string
balkon_smoke
  • 1,136
  • 2
  • 10
  • 25
2

If you're trying to remove the double quotes try following

  var Stringstr = "\"I am here\"";
  var mystring = String(Stringstr);
  mystring = mystring.substring(1, mystring.length - 1);
  alert(mystring);
1

This works...

var string1 = "'foo'";
var string2 = '"bar"';

function removeFirstAndLastQuotes(str){
  var firstChar = str.charAt(0);
  var lastChar = str[str.length -1];
  //double quotes
  if(firstChar && lastChar === String.fromCharCode(34)){
    str = str.slice(1, -1);
  }
  //single quotes
  if(firstChar && lastChar === String.fromCharCode(39)){
    str = str.slice(1, -1);
  }
  return str;
}
console.log(removeFirstAndLastQuotes(string1));
console.log(removeFirstAndLastQuotes(string2));
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
1
var expressionWithoutQuotes = '';
for(var i =0; i<length;i++){
    if(expressionDiv.charAt(i) != '"'){
        expressionWithoutQuotes += expressionDiv.charAt(i);
    }
}

This may work for you.

Splinker P
  • 11
  • 1
1

Use replaceAll

const someStr = 'He said "Hello, my name is Foo"';

console.log(someStr.replaceAll('"', '')); 

// => 'He said Hello, my name is Foo'
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67
0

This simple code will also work, to remove for example double quote from a string surrounded with double quote:

var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"(.+)"/g, '$1'));
Amaynut
  • 4,091
  • 6
  • 39
  • 44
0

this code is very better for show number in textbox

$(this) = [your textbox]

            var number = $(this).val();
            number = number.replace(/[',]+/g, '');
            number = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            $(this).val(number); // "1,234,567,890"
Ali Alizadeh
  • 326
  • 2
  • 6
0

If you want to be old school, go with REGEX 1,$s/"//g

alexw1
  • 9
  • 1
0

I may have found the code to remove a Single (or more) double quote character(s) from a Batch variable (based on a combination of everyone else's good work).

set test=SomeInputString with one " or more "characters" inside the string

:SINGLEDoubleQUOTERemover
Setlocal EnableDelayedExpansion
SET test=!test:"=!
::If the variable/input is empty to start with you must run the command twice...
SET test=!test:"=!
Setlocal DisableDelayedExpansion
ECHO %test%
::If the input is empty it ends up with a single = in the variable
IF "%test%"=="=" GOTO :EXIT
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34518629) – Ferris Jun 12 '23 at 17:38
  • Sorry but the OP's question refers to JavaScript. – Ferris Jun 12 '23 at 17:40
-8

Please try following regex for remove double quotes from string .

    $string = "I am here";
    $string =~ tr/"//d;
    print $string;
    exit();