Split a String into an Array of Words in JavaScript
Last Updated :
01 Feb, 2024
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.
Using the split() method
Using split()
method with a chosen separator such as a space (‘ ‘). It offers a simple and versatile way to break a string into an array of distinct elements. The split() method is commonly used to split the string into an array of substrings by using specific separators.
Example: The below code Splits a string into an array of words using the split() method.
Javascript
const string = `GeeksforGeeks is a leading platform that
provides computer science resources`;
const arrayofString = string.split( " " );
console.log(arrayofString);
|
Output
[
'GeeksforGeeks',
'is',
'a',
'leading',
'platform',
'that',
'\nprovides',
'computer',
'science',
'resources'
]
Using match() method with regular expression
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.
Javascript
const string = `GeeksforGeeks is a leading platform
that provides
computer science resources`;
const arrayOfString = string.match(/\b\w+\b/g);
console.log(arrayOfString);
|
Output
[
'GeeksforGeeks',
'is',
'a',
'leading',
'platform',
'that',
'provides',
'computer',
'science',
'resources'
]
Using spread operator with regex and match()
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
Javascript
const sentence = "Geeks for Geeks" ;
const wordsArray = [...sentence.match(/\S+/g)];
console.log(wordsArray);
|
Output
[ 'Geeks', 'for', 'Geeks' ]
Share your thoughts in the comments
Please Login to comment...