Search code examples
javascriptregextrim

How can I trim a specific character off the start & end of a string?


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.


Solution

  • 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