Split a String into an Array of Words in JavaScript
Last Updated :
19 Nov, 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.
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.
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'
]
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.
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'
]
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.
JavaScript
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.
JavaScript
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.
JavaScript
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.
JavaScript
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.
JavaScript
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.
JavaScript
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.
JavaScript
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.
JavaScript
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'
]
Similar Reads
Split an Array into Chunks in JavaScript
Here are different methods to split an array into chunks in JavaScript.1. Using slice() MethodThe array slice() method returns a new array containing the selected elements. This method selects the elements starting from the given start argument and ends at, but excluding the given end argument. Synt
3 min read
How To Split a String Into Segments Of n Characters in JavaScript?
When working with JavaScript, you might encounter a situation where you need to break a string into smaller segments of equal lengths. This could be useful when formatting a serial number, creating chunks of data for processing, or splitting a long string into manageable pieces. In this article, we
6 min read
Split JavaScript Array in Chunks Using Lodash?
When working with arrays in JavaScript, you may encounter situations where you need to split an array into smaller chunks. This can be particularly useful when dealing with large datasets or when performing operations in a more manageable and efficient manner. The Lodash library provides a convenien
2 min read
JavaScript - How to Count Words of a String?
Here are the various methods to count words of a string in JavaScript.1. Using split() MethodThe simplest and most common approach is to use the split() method to divide the string into an array of words and count the length of the array.JavaScriptconst count = (s) => s.trim().split(/\s+/).length
3 min read
How to transform a JavaScript iterator into an array ?
The task is to convert an iterator into an array, this can be performed by iterating each value of the iterator and storing the value in another array.These are the following ways we can add an iterator to an array:Table of ContentUsing Symbol iterator PropertyUsing Array.from MethodUsing the Spread
3 min read
How to Store an Object Inside an Array in JavaScript ?
Storing an object inside an array in JavScript involves placing the object as an element within the array. The array becomes a collection of objects, allowing for convenient organization and manipulation of multiple data structures in a single container. Following are the approaches through which it
3 min read
How to Push an Array into Object in JavaScript?
To push an array into the Object in JavaScript, we will be using the JavaScript Array push() method. First, ensure that the object contains a property to hold the array data. Then use the push function to add the new array in the object.Understanding the push() MethodThe array push() method adds one
2 min read
JavaScript - Insert a String at a Specific Index
These are the following methods to insert a string at a specific index in JavaScript:1. Using the slice() MethodInserting a string using the slice() method involves splitting the original string into two parts: one before the insertion point and one after. The new string is then placed between these
3 min read
Find Word Character in a String with JavaScript RegExp
Here are the different ways to find word characters in a string with JavaScript RegExp1. Using \w to Find Word CharactersThe \w metacharacter in regular expressions matches any word character, which includes:A to Z (uppercase letters)a to z (lowercase letters)0 to 9 (digits)Underscore (_)You can use
3 min read
JavaScript - Characterrs to Opposite Case in a String
Here are the various approaches to convert each character of a string to its opposite case (uppercase to lowercase and vice versa).Using for Loop and if-else Condition - Most CommonIn this approach, we iterate through each character of the string. Using an if-else statement, it checks if each charac
3 min read