Remove leading comma from a string

Remove leading comma from a string

I have the following string:
“,’first string’,’more’,’even more'”

I want to transform this into an Array but obviously this is not valid due to the first comma. How can I remove the first comma from my string and make it a valid Array?
I’d like to end up with something like this:
myArray = [‘first string’,’more’,’even more’]


Solution 1:

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.

Solution 2:

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


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);

Solution 3:

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.

Related:  What does the leading semicolon in JavaScript libraries do?

Solution 4:


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

I’ll be back.

Solution 5:

Assuming the string is called myStr:

// Strip start and end quotation mark and possible initial comma

// Split stripping quotations

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.

Solution 6:

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.