Horje
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. 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' ]

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.

Example: To demonstrate splitting a sentence into an array of words using For Loop.

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' ]

Using the 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.

Example: To demonstrate splitting a sentence into an array of words using the reduce() method

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' ]

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.

Example: The below code demonstrates how to split a string into an array of words using the Array.from() method with a regular expression.

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'
]

Using filter() Method with split()

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.

Example: To demonstrate splitting a sentence into an array of words using filter() method with split():

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'
]

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.

Example: Using Multiple Delimiters

The following code demonstrates how to split a string into an array of words using split() with a regular expression that matches multiple delimiters.

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' ]

Using the map() Method with trim()

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.

Example: To demonstrate splitting a sentence into an array of words using map() method with trim():

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'
]

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.

Example: The below code demonstrates splitting a sentence into an array of words using the flatMap() method.

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'
]



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
What is a Set in JavaScript? What is a Set in JavaScript?
Is set Ordered in JavaScript ? Is set Ordered in JavaScript ?
What is () =&gt; in JavaScript ? What is () =&gt; in JavaScript ?
What is the pop() method used for in JavaScript Arrays ? What is the pop() method used for in JavaScript Arrays ?
What is the use of the push() method in JavaScript Arrays ? What is the use of the push() method in JavaScript Arrays ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15