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.
1. Using 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.
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' ]
2. 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.
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' ]
3. Using Spread Operator with Regex and match() Method
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.
const sentence = "Geeks for Geeks";
const wordsArray = [...sentence.match(/\S+/g)];
console.log(wordsArray);
Output
[ 'Geeks', 'for', 'Geeks' ]
4. Using a For Loop
In this approach we iterate through each character using for loop and we check each character, if a space is encountered, it will be added to words array. If the character is not a space it will be added to the current word.
function splitStringIntoWords(str) {
let words = [];
let word = '';
for (let i = 0; i < str.length; i++) {
if (str[i] === ' ') {
if (word !== '') {
words.push(word);
word = '';
}
} else {
word += str[i];
}
}
if (word !== '') {
words.push(word);
}
return words;
}
let str = "Welcome to geeks for geeks";
let result = splitStringIntoWords(str);
console.log(result);
Output
[ 'Welcome', 'to', 'geeks', 'for', 'geeks' ]
5. Using reduce() Method
The reduce () method can be used to split a string into an array of words by iterating through each character and building words based on spaces or other separators. This method provides a functional approach to string manipulation.
function splitStringWithReduce(str) {
return str.split('').reduce((acc, char) => {
if (char === ' ') {
if (acc.word !== '') {
acc.words.push(acc.word);
acc.word = '';
}
} else {
acc.word += char;
}
return acc;
}, { words: [], word: '' }).words;
}
let str = "Hello from GeeksforGeeks";
let result = splitStringWithReduce(str);
console.log(result);
Output
[ 'Hello', 'from' ]
6. Using Array.from() Method
The Array.from() method can be combined with a regular expression to convert a string into an array of words. This approach leverages the ability of Array.from() to create a new array from any iterable or array-like object.
const string = `GeeksforGeeks is a leading platform
that provides
computer science resources`;
const arrayOfString = Array.from(string.matchAll(/\b\w+\b/g), match => match[0]);
console.log(arrayOfString);
Output
[ 'GeeksforGeeks', 'is', 'a', 'leading', 'platform', 'that', 'provides', 'computer', 'science', 'resources' ]
7. Using filter() with split() Methods
The filter() method can be used with the split() method to split a string into an array of words by filtering out any empty strings that may result from consecutive spaces or leading/trailing spaces.
const string = ` GeeksforGeeks is a leading platform that
provides computer science resources `;
const arrayOfWords = string.split(' ').filter(word => word !== '');
console.log(arrayOfWords);
Output
[ 'GeeksforGeeks', 'is', 'a', 'leading', 'platform', 'that', '\nprovides', 'computer', 'science', 'resources' ]
8. Using Multiple Delimiters
Sometimes, splitting a string into words involves dealing with multiple types of delimiters such as spaces, commas, periods, etc. Using a regular expression within the split() method allows for handling multiple delimiters effectively.
function splitStringWithMultipleDelimiters(str) {
// Split string by spaces, commas, periods, and other punctuation
return str.split(/[ ,.!?]+/).filter(Boolean);
}
// Usage example
const sentence = "Hello, world! How are you today?";
const wordsArray = splitStringWithMultipleDelimiters(sentence);
console.log(wordsArray); // Output: ["Hello", "world", "How", "are", "you", "today"]
Output
[ 'Hello', 'world', 'How', 'are', 'you', 'today' ]
9. Using map() with trim() Methods
The map () method can be combined with the trim () method to split a string into an array of words and remove any leading or trailing whitespace from each word. This approach is useful when dealing with strings where words might be separated by spaces and have unnecessary whitespace.
const string = ` GeeksforGeeks is a leading platform that
provides computer science resources `;
const arrayOfWords = string.split(' ').map(word => word.trim()).filter(word => word !== '');
console.log(arrayOfWords);
Output
[ 'GeeksforGeeks', 'is', 'a', 'leading', 'platform', 'that', 'provides', 'computer', 'science', 'resources' ]
10. Using flatMap() Method
The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. This approach can be leveraged to split a string into an array of words and filter out any empty strings in one step.
const string = ` GeeksforGeeks is a leading platform that
provides computer science resources `;
const arrayOfWords = string.split(' ').flatMap(word => word ? [word] : []);
console.log(arrayOfWords);
Output
[ 'GeeksforGeeks', 'is', 'a', 'leading', 'platform', 'that', '\nprovides', 'computer', 'science', 'resources' ]