get the first word of every line in javascript

You can use the split() and map() functions to achieve this result. First, you need to split the string into an array of lines using the split() function. Then, you can map() through this array and get the first word of each line using the split() function again, this time splitting each line on its whitespace characters. The first word will then be the first element in the resulting array. Here's the code:

index.tsx
const str = "Hello world\nHow are you?\nI am fine thank you\n";

const firstWords = str.split('\n').map(line => line.split(' ')[0]);

console.log(firstWords); // ["Hello", "How", "I"]
184 chars
6 lines

gistlibby LogSnag