Skip to main content

How to Split a String and Get the First or Last Element in JavaScript

A very common task in data parsing is to split a string by a delimiter and then immediately extract either the first or the last resulting part. For example, you might want to get the username from an email address (user@example.com -> user) or the file extension from a filename (report.pdf -> pdf).

This guide will teach you the modern and most direct methods for this task. You will learn how to use simple array indexing, the modern .at() method, and array destructuring to get the element you need.

The Core Method: String.prototype.split()

The String.prototype.split() method is the foundation for this task. It takes a separator (or "delimiter") and splits the string into an array of substrings.

let myString = 'a,b,c';
let separator = ',';

let parts = myString.split(separator);

console.log(parts);

Output:

['a', 'b', 'c']
note

Once you have this array, you can use standard array methods to access its elements.

Getting the First Element

The most direct way to get the first element of any array is to access it by its index.

let email = 'user@example.com';

// split() returns an array, and [0] accesses the first element.
let username = email.split('@')[0];

console.log(username);

Output:

user
note

This is the most common, readable, and performant way to get the first element.

Alternative: Array Destructuring

A modern alternative is to use array destructuring, which can be very readable if you only need the first part.

let email = 'user@example.com';

// The first element of the split array is assigned to the `username` variable.
let [username] = email.split('@');

console.log(username);

Output:

user

Getting the Last Element

Getting the last element is just as simple with modern array methods.

The Array.prototype.at() method was introduced in ES2022 and is the most concise and readable way to get the last element of an array. You simply pass it -1.

let filename = 'document.report.pdf';

// .at(-1) gets the last element from the array returned by split().
let extension = filename.split('.').at(-1);

console.log(extension);

Output:

pdf

Alternative (Classic): Using length

Before .at() was available, the standard way was to calculate the last index using the array's length property. This is more verbose and requires an intermediate variable.

let filename = 'document.report.pdf';
let parts = filename.split('.');

let extension = parts[parts.length - 1];

console.log(extension);

Output:

pdf
note

For this task, the .at(-1) method is clearly superior.

How to Handle the "Delimiter Not Found" Edge Case

A robust script must handle the case where the delimiter does not exist in the string. Fortunately, all the recommended methods handle this gracefully.

When split() is called with a delimiter that isn't found, it returns an array containing just the original string.

let str = 'filename';

let parts = str.split('.');
console.log(parts); // Output: ['filename']

// Getting the first element works as expected.
console.log(parts[0]); // Output: filename

// Getting the last element also works as expected.
console.log(parts.at(-1)); // Output: filename

Output:

['filename']
filename
filename

Because of this predictable behavior, you often don't need to add an extra if statement to check if the delimiter exists.

Conclusion

Splitting a string to get the first or last part is a simple task with clear, modern solutions in JavaScript.

  • To get the first element, the recommended best practice is to use simple array indexing: string.split(separator)[0].
  • To get the last element, the modern and recommended best practice is to use the .at() method: string.split(separator).at(-1).

These methods are concise, highly readable, and handle edge cases gracefully, making them the ideal choice for this common parsing task.