JavaScript - Extract First Word from a String
Here are the different methods to extract the first word from a string
Using split() Method - Most Popular
The split() method splits the string into an array of words based on spaces, and the first element of this array is the first word.
const s1 = "Hello World, welcome to GeeksforGeeks";
const s2 = s1.split(" ")[0];
console.log(s2);
Output
Hello
Using substring() and indexOf() Methods
Using indexOf() we can find the first space, then extracts everything before the space using substring(). This approach is useful if you need only the first word without further splitting.
const s1 = "Hello World, welcome to GeeksforGeeks";
// Extract the first word
const s2 = s1.indexOf(" ");
const s3 = s2 === -1 ? s1 : s1.substring(0, s2);
console.log(s3);
Output
Hello
Using Regular Expression
A regular expression can match the first sequence of non-space characters.
const s1 = "Hello World, welcome to GeeksforGeeks";
// Extract the first word using regex
const s2 = s1.match(/\S+/)[0];
console.log(s2);
Output
Hello
Using slice() and indexOf()
Similar to substring(), slice() can be used to extract characters up to the first space. This approach can also handle cases where there's no space in the string.
const s1 = "Hello World, welcome to GeeksforGeeks";
// Extract the first word
const s2 = s1.slice(0, s1.indexOf(" ") !== -1 ? s1.indexOf(" ") : s1.length);
console.log(s2);
Output
Hello
Using trim() and split()
You can first trim the whitespace using trim(), then split() to extract the first word.
const s1 = "Hello World, welcome to GeeksforGeeks";
const s2 = s1.trim().split(" ")[0];
console.log(s2);
Output
Hello
Using Array.from() and for...of Loop
This method converts the string into an array using Array.from(), then iterates character by character to get the first word manually.
const s1 = "Hello World, welcome to GeeksforGeeks";
// Extract first word manually
let s2 = '';
for (const char of Array.from(s1)) {
if (char === ' ') break;
s2 += char;
}
console.log(s2);
Output
Hello
Importance of Extracting the First Word in JavaScript
Extracting the first word from a string is useful for
- Data Parsing: Extracting titles or key information from strings.
- Improving User Interactions: Displaying simplified information for readability.
- Text Processing: Assisting in tasks like summarizing or analyzing data.