JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

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

To split a string, you use the split() method.

When you call the split() method, it splits a string based on the separator passed to it. As a result, it returns an array of substrings. So, to access the first array element, you have to use index position 0.

Suppose you want to split a string by space and get the first element, then run the following code:

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

console.log(arr); //["Doughnut", "Chocolate", "Pastry"]
console.log(`First element: ${arr[0]}`); //"First element: Doughnut"

You can see that the split() method has split the string into an array. The first element is accessed using the square bracket notation.

In JavaScript, the array follows zero-based indexing. This means the first element is at 0th position, the second element is at 1st position, and the last element is at (array.length - 1) position.

Recommended Posts