Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 931
Danny Beckett Avatar asked Aug 16 '13 07:08

Danny Beckett


People also ask

How do I cut a specific character from a string?

You can easily remove white spaces from both ends of a string by using the String. Trim method, as shown in the following example. String^ MyString = " Big "; Console::WriteLine("Hello{0}World! ", MyString); String^ TrimString = MyString->Trim(); Console::WriteLine("Hello{0}World!

How do you trim a character in JavaScript?

JavaScript provides three functions for performing various types of string trimming. The first, trimLeft() , strips characters from the beginning of the string. The second, trimRight() , removes characters from the end of the string. The final function, trim() , removes characters from both ends.

How do I remove a specific character from a string in Python?

In Python you can use the replace() and translate() methods to specify which characters you want to remove from the string and return a new modified string result. It is important to remember that the original string will not be altered because strings are immutable.

How do I remove the start and end of a string?

Use the trim() method to remove the line breaks from the start and end of a string, e.g. str. trim() . The trim method removes any leading or trailing whitespace from a string, including spaces, tabs and all line breaks.


1 Answers

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

like image 163
Danny Beckett Avatar answered Nov 04 '22 16:11

Danny Beckett