9

How can I remove a specific character, a double-quote ("), appearing any number of times, from the start and end of a string?

I had a look at string.trim(), which trims any whitespace characters, but it's not possible to provide an optional argument with " as the needle to search for.

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
  • possibly adapt this shim for trim to shave what you crave http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript – Paul Aug 16 '13 at 07:39
  • @Paul That was for the days when there was no native `string.trim()` function. This exists now, but it's only for whitespace. – Danny Beckett Aug 16 '13 at 07:40
  • Adapting `this.replace(/^\s+|\s+$/g, '')` means changing the `\s+` to `"+` ... which then matches your answer, actually. So now we have some confirmation. – Paul Aug 16 '13 at 07:45

1 Answers1

29

You can use RegEx to easily conquer this problem:

myString = myString.replace(/^"+|"+$/g, '');

You can substitute the " with any character (be careful, some characters need to be escaped).

Here's a demo on JSFiddle.


An explanation of the regular expression:

/ - start RegEx (/)

^"+ - match the start of the line (^) followed by a quote (") 1 or more times (+)

| - or

"+$ - match a quote (") 1 or more times (+) followed by the end of the line ($)

/ - end RegEx (/)

g - "global" match, i.e. replace all

Community
  • 1
  • 1
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134