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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s… Read more: JavaScript – Shuffle an array in a random order