Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading comma from a string

People also ask

How do I remove a comma from a string in Python?

sub() function to erase commas from the python string. The function re. sub() is used to swap the substring. Also, it will replace any match with the other parameter, in this case, the null string, eliminating all commas from the string.

How do I remove the last comma character from a string?

To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed.


To remove the first character you would use:

var myOriginalString = ",'first string','more','even more'"; 
var myString = myOriginalString.substring(1);

I'm not sure this will be the result you're looking for though because you will still need to split it to create an array with it. Maybe something like:

var myString = myOriginalString.substring(1);
var myArray = myString.split(',');

Keep in mind, the ' character will be a part of each string in the split here.


In this specific case (there is always a single character at the start you want to remove) you'll want:

str.substring(1)

However, if you want to be able to detect if the comma is there and remove it if it is, then something like:

if (str[0] == ',') { 
  str = str.substring(1);
}

One-liner

str = str.replace(/^,/, '');

I'll be back.


var s = ",'first string','more','even more'";

var array = s.split(',').slice(1);

That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.


Assuming the string is called myStr:

// Strip start and end quotation mark and possible initial comma
myStr=myStr.replace(/^,?'/,'').replace(/'$/,'');

// Split stripping quotations
myArray=myStr.split("','");

Note that if a string can be missing in the list without even having its quotation marks present and you want an empty spot in the corresponding location in the array, you'll need to write the splitting manually for a robust solution.


var s = ",'first string','more','even more'";  
s.split(/'?,'?/).filter(function(v) { return v; });

Results in:

["first string", "more", "even more'"]

First split with commas possibly surrounded by single quotes,
then filter the non-truthy (empty) parts out.


To turn a string into an array I usually use split()

> var s = ",'first string','more','even more'"
> s.split("','")
[",'first string", "more", "even more'"]

This is almost what you want. Now you just have to strip the first two and the last character:

> s.slice(2, s.length-1)
"first string','more','even more"

> s.slice(2, s.length-2).split("','");
["first string", "more", "even more"]

To extract a substring from a string I usually use slice() but substr() and substring() also do the job.