How to use trim() and split() In Javascript
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.
function extractFirstWord(str) {
return str.trim().split(' ')[0];
}
console.log(extractFirstWord(" Hello world! "));
console.log(extractFirstWord("JavaScript is awesome"));
Output
Hello
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