Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu September 20, 2022 . #Element . #HowTo

Split a String and Get the First Element in Javascript

In this article, you will learn how to split a string and get the first element using Javascript.

For example, if the string is My name is Apu. , then to get the first element My , we will use the split() method.

Demo : split string & get first element / word.
let myString = "My name is Apu";
alert(myString.split(' ')[0])
Try it Yourself »
  1. First, we will create a variable with its value My name is Apu.
    let myString = "My name is Apu";
  2. Now if we use the split() method with the variable myString e.g. myString.split(' '), then it will return the following array .
    🔽Array
     0:"My"
     1:"name"
     2:"is"
     3:"Apu"
     length:4
    
    We have passed the split() method a blank space as a parameter. So , it splits the string on each blank space and returns the above array.
    let myArray = myString.split(' ')
  3. As we got an array of words, so we can easily get the first element of that array by passing its index number.

  4. let myArray = myString.split(' ')
    alert(myArray[0])
    myArray[0] returns the first element of that array. To get the second element (item) of that array , use the index number of 1 e.g. myArray[1]

How to get the last item of the string.

To get an element (item) of the array, we can pass an index number manually. But if we have no idea about how many items can be there, in this case, we can use the length of the array. e.g. myArray[myArray.length]

But there is a problem. In Javascript , the first element in an array has an index of 0, and the last item has an index of array.length - 1.

So, to get the last element of the above array, we have to use the following code.

let myString = "My name is Apu" 
let myArray = myString.split(' ')
alert(myArray[myArray.length - 1])
save
listen
AI Answer
Write Your Answer
loading
back
View All