How to use spread operator with regex and match() In Javascript
Using Spread operator with regex can efficiently split a string into an array of words. This technique identifies word boundaries and spreads the matched substrings into an array of words.
Example: To demonstrate splitting a sentence into an array of words using the spread operator
const sentence = "Geeks for Geeks";
const wordsArray = [...sentence.match(/\S+/g)];
console.log(wordsArray);
Output
[ 'Geeks', 'for', 'Geeks' ]
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. This results in an array where each element represents a word from the original string. This can be achieved by using the following methods.
Table of Content
- Using the split() method
- Using match() method with regular expression
- Using spread operator with regex and match()
- Using a For Loop
- Using the reduce() Method