How to use substring() and indexOf() Methods In Javascript
In this approach, we are using substring() and indexOf() methods to extract the first word from the string. The substring() method here is used to extract a substring from the beginning of the input string up to that index. The indexOf() method is used to find the index of the first space character in the input string.
Syntax
string.substring(string.indexOf(searchValue, startIndex), endIndex);
Example: In this example, we will be extracting the first word from a string using substring() and indexOf() Methods.
let str = "Geeks For Geeks";
let index = str.indexOf(' ');
let res =
str.substring(0, index !== -1 ?
index : str.length);
console.log(res);
Output
Geeks
JavaScript Program to Extract First Word from a String
In this article, we have to extract the first word from the input string in JavaScript language. Below is an example for better understanding.
Examples:
Input: Geeks for Geeks Output: Geeks Input: I Love India Output: I
Contact Us