Split a String and get the First Array Element in JS

avatar

Borislav Hadzhiev

Last updated: Aug 27, 2022

banner

Photo from Unsplash

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 argument 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(','))

We can access the element at index 0 to get the first element in the array.

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 this case it 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.