Skip to content Skip to sidebar Skip to footer

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

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 valuefunction 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.

Solution 3:

You can use a regex to match the two strings before and after the first comma:

var v = "boy, girl, dog, cat";
var strings = v.match(/([^,]*),(.*)/);

Now strings will be a three element array where

  • strings[0] contains the full string
  • strings[1] contains the string before the first comma
  • strings[2] contains everything after the first comma

Solution 4:

You can create an array in a lazy way and then retrieve just the first element.

var ArrayFromString = "boy, girl, dog, cat".split(",");
firstElement = ArrayFromString.pop();
alert(firstElement); //boy
alert(ArrayFromString); //girl, dog, cat​​​​​​​​​​​​​​​​​

Solution 5:

Yet another option is to split the array, get first and join the rest:

var my_string = "boy, girl, dog, cat";
var splitted = my_string.split(',');
var first_item = splitted.shift();
var rest_of_the_items = splitted.join(',');

console.log(first_item); // 'boy'console.log(rest_of_the_items); // 'girl, dog, cat'

Post a Comment for "Get First And Rest Of String From Comma Separated Values In Javascript"