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"