views:

167

answers:

5

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 coma. How can I remove the first coma from my string and make it a valid Array?

Get something like this:

myArray = ['first string','more','even more']

Thank you.

+5  A: 

To remove the first character you would use:

myOriginalString = ",'first string','more','even more'"; 
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:

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

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

Joel Etherton
+1  A: 
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.

EMMERICH
+2  A: 

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.substring(0, 1) == ',') { 
  str = str.substring(1);
}
thomasrutter
+1 for the conditional
Joel Etherton
A: 

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.

Fabian Jakobs
A: 

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.

jjrv