javascript - Remove leading comma from a string

ID : 20236

viewed : 7

Tags : javascriptarraysstringjavascript

Top 5 Answer for javascript - Remove leading comma from a string

vote vote

100

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.

vote vote

89

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

74

One-liner

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

I'll be back.

vote vote

62

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.

vote vote

50

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.

Top 3 video Explaining javascript - Remove leading comma from a string

Related QUESTION?