To split a JavaScript string into words, you can use the split() method, which divides a string into an array of substrings based on a specified separator. If you want to split the string into words, you can use a regular expression as the separator to split the string wherever there are spaces or other whitespace characters. Here’s an example:
const sentence = "This is a sample sentence";
const words = sentence.split(/\s+/);
console.log(words);
In this example, \s+ is a regular expression that matches one or more whitespace characters (spaces, tabs, newlines, etc.). So, the split() method will split the string sentence into an array of words wherever there are one or more whitespace characters.
The output will be:
["This", "is", "a", "sample", "sentence"]
Each element of the resulting array will contain one word from the original string.