Split a String and get the First Array Element in JS

avatar

Borislav Hadzhiev

Wed Nov 17 20212 min read

banner

Photo by Jamie Street

Split a String and get the First Array Element #

To split a string and get the first element of the array, call the split() method on the string, passing it the separator as a parameter, and access the array element at index 0. For example, str.split(',')[0] splits the string on each comma and returns the first array element.

index.js
const str = 'apple,banana,melon'; const split = str.split(','); console.log(split); // ๐Ÿ‘‰๏ธ ['apple', 'banana', 'melon'] // โœ…๏ธ get first const first = split[0]; console.log(first); // ๐Ÿ‘‰๏ธ "apple" // โœ…๏ธ get last const last = split[split.length - 1]; console.log(last); // ๐Ÿ‘‰๏ธ "melon"

The only parameter we passed to the String.split method is the separator, on which we want to split the string.

In the example, we split the string on each comma to get an array of substrings.

index.js
const str = 'apple,banana,melon'; // ๐Ÿ‘‡๏ธ ['apple', 'banana', 'melon'] console.log(str.split(','))

To get the first element from the array, we can access the element at position 0.

Indexes are zero-based in JavaScript, meaning the first element in an array has an index of 0, and the last - an index of array.length - 1.
index.js
const str = 'apple,banana,melon'; console.log(str.split(',')[0]); // ๐Ÿ‘‰๏ธ "apple"

An alternative approach is to use the shift() method.

To split a string and get the first array element:

  1. Call the split() method on the string to get an array of substrings.
  2. Call the shift() method on the array.
  3. The shift method removes and returns the first element of the array.
index.js
const str = 'apple,banana,melon'; const split = str.split(','); console.log(split); // ๐Ÿ‘‰๏ธ ['apple', 'banana', 'melon'] // โœ…๏ธ get first const first = split.shift(); console.log(first); // ๐Ÿ‘‰๏ธ "apple" // โœ…๏ธ get last const last = split.pop(); console.log(last); // ๐Ÿ‘‰๏ธ "melon"

The Array.shift method removes the first element from the array and returns it.

The method mutates the original array in-place, but in our case this doesn't matter, because we're using a throwaway array.

Which approach you use is a matter of personal preference. I'd go with accessing the array at index 0 as I find it more direct and intuitive.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee