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
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
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
Convert Array to String in JavaScript In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen
7 min read
Javascript Program To Reverse Words In A Given String Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i"Examples:Â Input: s = "geeks quiz practice code"Â Output: s = "code practice quiz geeks"Input: s = "getting good at coding needs a lot of practice"Â Output: s = "pra
4 min read
JavaScript Program to Split a String into a Number of Sub-Strings Given a string, the task is to split the string into number of sub-strings using JavaScript. This task is common in scenarios where data needs to be segmented or processed in chunks. This article provides a flexible solution that can divide a given string into a desired number of smaller substrings,
2 min read
JavaScript - Convert String to Array Strings in JavaScript are immutable (cannot be changed directly). However, arrays are mutable, allowing you to perform operations such as adding, removing, or modifying elements. Converting a string to an array makes it easier to:Access individual characters or substrings.Perform array operations su
5 min read
JavaScript - Convert Comma Separated String To Array Here are the various methods to convert comma-separated string to array using JavaScript.1. Using the split() Method (Most Common)The split() method is the simplest and most commonly used way to convert a comma-separated string into an array. It splits a string into an array based on a specified cha
3 min read