JavaScript – Split a string into an array of words

In this post, we will see how we can split a string into an array of words in JavaScript. JavaScript allows us to split the string into an array of words using string manipulation techniques, such as using regular expressions or the split method.

Using split()

function splitIntoWords(str) {
  return str.split(/\s+/);
}

// Example usage
let sentence = "ES6 is quite powerful in iterating through objects";
let words = splitIntoWords(sentence);
console.log(words);

Output

["ES6", "is", "quite", "powerful", "in", "iterating", "through", "objects"]

Using Regular Expressions

let str = "Split this string!";
let wordsArray = str.match(/\b\w+\b/g);
console.log(wordsArray);

Output

["Split", "this", "string"]

Similar Reads