Open In App

JavaScript Program to Split a String into a Number of Sub-Strings

Last Updated : 08 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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, allowing for efficient manipulation or analysis of the data.

Split a String into Number of Sub-Strings using substring() Method

This approach divides the length of the string by the specified number of substrings to determine the approximate length of each substring. It then iteratively extracts substrings of equal length using the substring() method until the entire string is segmented.

Javascript




function splitString(str, splitCount) {
    const substrings = [];
    const substringLength = Math.ceil(str.length / splitCount);
    let startIndex = 0;
    for (let i = 0; i < splitCount; i++) {
        substrings.push(str.substring(startIndex, startIndex + substringLength));
        startIndex += substringLength;
    }
    return substrings;
}
  
// Driver code
console.log(splitString("hello world", 3));


Output

[ 'hell', 'o wo', 'rld' ]

Split a String into Number of Sub-Strings using slice() Method

This method divides the length of the string by the specified number of substrings to determine the approximate length of each substring. It then utilizes the slice() method to extract substrings of equal length iteratively until the entire string is segmented

Example:

Javascript




function splitString(str, splitCount) {
    const substrings = [];
    const substringLength = Math.ceil(str.length / splitCount);
    let startIndex = 0;
    for (let i = 0; i < splitCount; i++) {
        substrings.push(str.slice(startIndex, startIndex + substringLength));
        startIndex += substringLength;
    }
    return substrings;
}
  
// Driver code
console.log(splitString("hello world", 3));


Output

[ 'hell', 'o wo', 'rld' ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads