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.

JavaScript
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


Similar Reads

Examples of Extracting First Word from a String

Table of Content Using split() MethodUsing substring() and indexOf() MethodsUsing Regular ExpressionUsing slice() and indexOf() MethodsUsing for loopUsing trim() and split()...

Using split() Method

In this approach, we are using the split() method to extract the first word from the input string. The split() method in JS is used to split the string into the array of substrings and from this substring, we extract the first word which is stored at the 0th index....

Using substring() and indexOf() Methods

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....

Using Regular Expression

In this approach, we are using the regular expression ‘/^\S+/‘ that is used with the match() method to find and print the dist sequence of non-space characters at the beginning of the input string. If a match is found then it assigns that match to the output variable else it assigns the empty string....

Using slice() and indexOf() Methods

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....

Using for loop

Extract the first word from a string using a for loop. Iterate through characters until encountering a space. Concatenate characters to form the first word....

Using trim() and split()

To extract the first word from a string using trim() and split():...

Contact Us