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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read
Web Development Technologies Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.To better understand the foundation of web devel
7 min read