How to use slice() and indexOf() Methods In Javascript
In this approach, the slice() method and indexOf() methods are used to extract the first word from the input string. Here, the indexOf() method is used to locate the index of the first space character in the input string, and the slice() method is used to extract the desired substring from the start of the input string tup to the index computed by indexOf() method.
Syntax
string.slice(0, string.indexOf(' ')) || string;
Example: In this example, we will be extracting the first word from a string using slice() and indexOf() Methods.
let str = "Geeks For Geeks";
let index = str.indexOf(' ');
let res =
index !== -1 ?
str.slice(0, index) : str;
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