How to use match() method with regular expression In Javascript
The regular expression can be used with the match() method to assert the word boundaries while ensuring that only the whole word is matched. This results in the array containing each word of the string as a separate element of the array.
Example: The below code splits the string using the match() method along with the regular expression.
const string = `w3wiki is a leading platform
that provides
computer science resources`;
const arrayOfString = string.match(/\b\w+\b/g);
console.log(arrayOfString);
Output
[ 'w3wiki', 'is', 'a', 'leading', 'platform', 'that', 'provides', 'computer', 'science', 'resources' ]
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