Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Split string into equal parts JavaScript
In JavaScript, splitting a string into equal parts can be accomplished in several ways. This article demonstrates how to split a string into n equal parts using an alternating pattern that takes characters from both ends of the string.
Problem Statement
We need to write a JavaScript function that takes a string and a number n as arguments, where n exactly divides the string length. The function should return an array of n strings of equal length, formed by alternating between the first and last characters of the remaining string.
For example:
If the string is "helloo" and the number is 3 Our output should be: ["ho", "eo", "ll"]
Each substring contains exactly (string length / n) characters, formed by taking characters alternately from the beginning and end of the string.
Using Alternating Pattern Method
This approach uses shift() and pop() methods to take characters from both ends alternately:
const str = 'helloo';
const splitEqual = (str, n) => {
if(str.length % n !== 0){
return false;
}
const len = str.length / n;
const strArray = str.split("");
const arr = [];
let i = 0, char;
while(strArray.length){
if(i % 2 === 0){
char = strArray.shift();
}else{
char = strArray.pop();
}
if(i % len === 0){
arr[i / len] = char;
}else{
arr[Math.floor(i / len)] += char;
}
i++;
}
return arr;
};
console.log(splitEqual(str, 3));
[ 'ho', 'eo', 'll' ]
Simple Sequential Split Method
For a more straightforward approach that splits the string sequentially:
const splitEqualSequential = (str, n) => {
if(str.length % n !== 0){
return false;
}
const len = str.length / n;
const result = [];
for(let i = 0; i
[ 'he', 'll', 'oo' ]
[ 'javas', 'cript' ]
How the Alternating Pattern Works
The alternating pattern algorithm works as follows:
- Convert the string to an array for easy manipulation
- Alternate between taking characters from the beginning (shift) and end (pop)
- Distribute characters evenly across n output strings
- Each output string gets exactly (total length / n) characters
Comparison
| Method | Pattern | Complexity | Use Case |
|---|---|---|---|
| Alternating | From both ends | O(n) | Specific alternating requirements |
| Sequential | Left to right | O(n) | Simple equal splitting |
Conclusion
Both methods effectively split strings into equal parts. Use the alternating pattern when you need characters from both ends, or the sequential method for straightforward equal division of strings.
