split a string into an array of words in javascript

To split a string into an array of words in JavaScript, you can use the split() method along with a regular expression.

index.tsx
const str = "Hello world, how are you?";
const words = str.split(/\s+/);

console.log(words);
// Output: ["Hello", "world,", "how", "are", "you?"]
147 chars
6 lines

In the above example, we're using the split() method with a regular expression \s+, which matches one or more whitespace characters (spaces, tabs, etc.). This splits the string into an array of words and assigns it to the words variable.

You can then access each word in the array using its index, like words[0], words[1], and so on.

gistlibby LogSnag