How to use for loop In Javascript
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.
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
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