The Wayback Machine - https://web.archive.org/web/20240815135456/https://www.geeksforgeeks.org/javascript-program-to-extract-first-word-from-a-string/
Open In App

JavaScript Program to Extract First Word from a String

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Examples of Extracting First Word from a String

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.

Syntax

string.split(separator, limit);

Example: In this example, we will be extracting the first word from a string using the split() Method.

JavaScript
let str = "Geeks For Geeks";
let res = str.split(' ')[0];
console.log(res);

Output
Geeks

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.

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

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.

Syntax

string.match(expression);

Example: In this example, we will be extracting the first word from a string using regular expression.

JavaScript
let str = "Geeks For Geeks";
let match = str.match(/^\S+/);
let res = match ? match[0] : '';
console.log(res);

Output
Geeks

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.

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.

JavaScript
let str = "Geeks For Geeks";
let index = str.indexOf(' ');
let res = 
    index !== -1 ? 
        str.slice(0, index) : str;
console.log(res);

Output
Geeks

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.

Syntax

for (statement 1 ; statement 2 ; statement 3){
code here...
}

Example: In this example we are following above mentioned apporach.

JavaScript
function extractFirstWord(str) {
    let word = "";
    for (let i = 0; i < str.length; i++) {
        // Append characters to the word until a space is encountered
        if (str[i] !== " ") {
            word += str[i];
        } else {
            // Break the loop when a space is encountered
            break;
        }
    }
    return word;
}

// Example usage
const string = "Geeks for Geeks";
const firstWord = extractFirstWord(string);
console.log(firstWord); //

Output
Geeks

Using trim() and split()

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

  • Trim the string to remove any leading or trailing whitespace.
  • Split the trimmed string by spaces.
  • Return the first element of the resulting array.

Example: The extractFirstWord function trims leading and trailing spaces, then splits the string by spaces, returning the first element. Outputs “Hello” and “JavaScript” for the respective input strings.

JavaScript
function extractFirstWord(str) {
    return str.trim().split(' ')[0];
}

console.log(extractFirstWord("  Hello world!  ")); 
console.log(extractFirstWord("JavaScript is awesome")); 

Output
Hello
JavaScript

Using Array.from() and for…of Loop

In this approach, we are using the Array.from() method to convert the input string into an array of characters, and then using a for…of loop to iterate through each character until we encounter a space. The characters before the space are concatenated to form the first word.

Syntax:

Array.from(string);for (variable of iterable) {  // code block to be executed}

Example: In this example, we will be extracting the first word from a string using the Array.from() method and a for…of loop.

JavaScript
function extractFirstWord(str) {
  let word = "";
  for (let char of Array.from(str)) {
    if (char !== " ") {
      word += char;
    } else {
      break;
    }
  }
  return word;
}

const string = "Geeks for Geeks";
const firstWord = extractFirstWord(string);
console.log(firstWord);

Output
Geeks

Approach 8: Using Array.prototype.findIndex() Method

In this approach, we will use the Array.prototype.findIndex() method to locate the index of the first space in the string. We will then use the slice() method to extract the first word from the string up to that index. This method is efficient and leverages JavaScript’s array methods for a clean solution.

Example:

JavaScript
function extractFirstWord(inputStr) {
    const firstSpaceIndex = Array.from(inputStr).findIndex(char => char === ' ');
    
    const firstWord = firstSpaceIndex !== -1 ? inputStr.slice(0, firstSpaceIndex) : inputStr;
    
    return firstWord;
}
const inputStr1 = 'Hello JavaScript';
const inputStr2 = 'SingleWord';
console.log(extractFirstWord(inputStr1)); 
console.log(extractFirstWord(inputStr2));

Output
Hello
SingleWord


Similar Reads

What is the difference between “word-break: break-all” versus “word-wrap: break-word” in CSS ?
The word-break property in CSS is used to specify how a word should be broken or split when reaching the end of a line. The word-wrap property is used to split/break long words and wrap them into the next line. Difference between the "word-break: break-all;" and "word-wrap: break-word;" word-break: break-all; It is used to break the words at any ch
2 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks
3 min read
JavaScript Program to Find the First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string. Examples: Input: “Ravi had been saying that he had been there”Output: hadInput: “Ravi had been saying that”Output: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUsing indexOf methodUsing Nested for loopUsing a Map
4 min read
JavaScript Program to Print the First Letter of Each Word
Printing the first letter of each word involves extracting the initial character from every word in a given string, typically accomplished by splitting the string into words and selecting the first character from each resulting word. Examples of Printing the First Letter of Each Word Table of Content Using for loop with split methodUsing forEach wi
3 min read
JavaScript Program to Extract Email Addresses from a String
In this article, we will explore how to extract email addresses from a string in JavaScript. Extracting email addresses from a given text can be useful for processing and organizing contact information. There are various approaches to extract email addresses from a string in JavaScript: Table of Content Using Regular ExpressionsSplitting and Filter
4 min read
Find the first occurrence of particular word in a given string using Vue.js filters
In this article, we are going to learn how to find the first occurrence of a particular word in a given string using filters in VueJS. Vue is a progressive framework for building user interfaces. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The fi
2 min read
JavaScript Program to Calculate the Frequency of Each Word in the Given String
Given a string, our task is to calculate the Frequency of Each Word in the Given String using JavaScript. Example:Input:"geeks for geeks is for geeks"Output:"geeks": 3 , "for": 2 , "is": 1 Below are the approaches for calculating the Frequency of Each Word in the Given String using JavaScript: Table of Content Using an Object Using Map Using reduce
3 min read
JavaScript Program to find Smallest and Largest Word in a String
We are going to discuss how can we find the Smallest and Largest word in a string. The word in a string which will have a smaller length will be the smallest word in a string and the word that has the highest length among all the words present in a given string will be the Largest word in a string. There are a few approaches by which we can find th
5 min read
JavaScript Program to Find the Most Frequent Word in a String
We will explore a couple of approaches to finding the most frequent word in a string and provide clear explanations along with practical examples. Determining the most frequent word in a string is a common task in text analysis and processing. In JavaScript, we can accomplish this task using various techniques. Identifying the most frequent word in
5 min read
How to extract date from a string in dd-mmm-yyyy format in JavaScript ?
In this article, we will see how to extract date from a given string of format "dd-mmm-yyyy" in JavaScript. We have a string, and we want to extract the date format "dd-mmm-yyyy" from the string. Example: // String str = "India got freedom on 15-Aug-1947" // Extracted date from given string in // "dd-mmm-yyyy" format date = 15-Aug-1947 Approach: Th
2 min read
three90RightbarBannerImg