Get first and rest of string from comma separated values in Javascript
Given a string like this:
"boy, girl, dog, cat"
What would be a good way to get the first word and the rest of them, so I could have this:
var first_word = "boy";
var rest = "girl, dog, cat";
Right now I have this:
my_string.split(",");
But that gives me all the words that are between the commas.
Solution 1:
You can use both split
and splice
:
var str = "boy, girl, dog, cat";
var arr = str.split(",");
var fst = arr.splice(0,1).join("");
var rest = arr.join(",");
Or similar
// returns an array with the extracted str as first value
// and the rest as second value
function cutFirst(str,token){
var arr = str.split(token);
var fst = arr.splice(0,1);
return [fst.join(""),arr.join(token)];
}
Solution 2:
Use a combination of substring()
(returning the substring between two indexes or the end of the string) and indexOf()
(returning the first position of a substring within another string):
var input = "boy, girl, dog, cat",
pos = input.indexOf( ',' );
console.log( input.substring( 0, pos ) );
console.log( input.substring( pos + 1 ) );
Maybe you want to add an trim()
call to the results to remove whitespaces.