JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to split a string and get the last element in JavaScript?

JavaScript String provides a split() method to split a string.

The split() method accepts a separator and returns an array of substrings. The separator works as a condition using which the string will be split. It can be a string or regular expression.

let arraySubstring = str.split(separator);

Once you have the array of substrings, to get the last element, you can follow any one of the two ways:

1. You call the pop() method, and it returns the last element of the array.

let str = "Doughnut Chocolate Pastry";
let arr = str.split(" ");

console.log(arr); //["Doughnut", "Chocolate", "Pastry"]

let lastElement = arr.pop();
console.log(`Last element: ${lastElement}`); //"Last element: Pastry"

2. Using the square bracket notation, you access the array element and pass (array.length - 1) value to it.

let str = "Doughnut Chocolate Pastry";
let arr = str.split(" ");

console.log(arr); //["Doughnut", "Chocolate", "Pastry"]

let lastElement = arr[arr.length - 1];
console.log(`Last element: ${lastElement}`); //"Last element: Pastry"

Recommended Posts