Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To get first word of string in javascript, use split(" ") method with 0 index value it will return first word from string. You have to only pass " " in split() method.

Let’s see short example to use split(" ") with with 0 index to get first word from string.

string.split(" ")[0];

Today, I’m going to show you How do I get first word of string in javascript, as above mentioned, I’m going to use the above-mentioned split() method.

Let’s start today’s tutorial how do you get first word of string in javascript?

Javascript get first word of string example

Here, we will take string variable with some data and use split() method to get first word of string.

let string = "Welcome to infinitbility";

let strArr = string.split(" ");

if(strArr.length > 0){
  console.log(strArr[0])
}

// Output
// 'Welcome'

***TIP: Before acceing any array value using index check length greater than 0 or not ***

Output

Javascript get first word of string example
Javascript get first word of string example

I hope it helps you, All the best đź‘Ť.