How to Extract a Word from a String in JavaScript?

Estimated read time 1 min read

You can extract a word from a string in JavaScript using regular expressions and the match() method. The regular expression \w+ matches one or more word characters (letters, digits, or underscores), and the match() method returns an array of all matches found in the string. Here’s an example code snippet to extract the first word from a string:

const str = "The quick brown fox jumps over the lazy dog.";

const matches = str.match(/\w+/);
const word = matches[0];
console.log(word); // output: "The"

In the above code, the match() method is used to find the first word in the str string. The regular expression \w+ matches one or more word characters (letters, digits, or underscores). The match() method returns an array of all matches found in the string. In this case, the array contains the single word “The”. The first element of the array is extracted and stored in the word variable using array indexing. Finally, the word variable is logged to the console. Note that this method extracts only the first word in the string. If you want to extract a specific word or all words in the string, you can modify the regular expression accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply