admin管理员组

文章数量:1277896

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

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

Share Improve this question asked Nov 12, 2012 at 9:19 Hommer SmithHommer Smith 27.9k62 gold badges176 silver badges307 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4

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

Use a bination 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.

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

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 ma
  • strings[2] contains everything after the first ma

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​​​​​​​​​​​​​​​​​

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'

const my_string = "boy, girl, dog, cat"; 
const splitted = my_string.split(',');
splitted.forEach(element => console.log(element));

You can also them like an array:

console.log(\`This is a ${splitted\[0\]}\`);

// expected output: "boy"

// expected output: " girl"

// expected output: " dog"

// expected output: " cat"

本文标签: Get first and rest of string from comma separated values in JavascriptStack Overflow