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
Breaking a string into chunks of defined length and removing spaces using JavaScript
We are required to write a JavaScript function that takes in a string sentence that might contain spaces as the first argument and a number as the second argument.
Our function should first remove all the spaces from the string and then break the string into a number of chunks specified by the second argument.
All the string chunks should have the same length with an exception of last chunk, which might, in some cases, have a different length.
Solution Approach
The solution involves two main steps:
- Remove all spaces using regex
/\s/g - Split the cleaned string into chunks using a loop and
slice()method
Example
Following is the complete implementation:
const num = 5;
const str = 'This is an example string';
const splitString = (str = '', num = 1) => {
// Remove all spaces from the string
str = str.replace(/\s/g, '');
const arr = [];
// Split string into chunks of specified length
for(let i = 0; i < str.length; i += num){
arr.push(str.slice(i, i + num));
}
return arr;
};
console.log(splitString(str, num));
[ 'Thisi', 'sanex', 'ample', 'strin', 'g' ]
How It Works
The function works in these steps:
-
str.replace(/\s/g, '')removes all whitespace characters globally - The loop increments by
numto create chunks of the specified size -
str.slice(i, i + num)extracts each chunk from positionitoi + num - The last chunk automatically handles remaining characters if the string length isn't divisible by
num
Alternative Example
Here's another example with different chunk size:
const text = 'JavaScript is awesome'; const chunkSize = 3; console.log(splitString(text, chunkSize));
[ 'Jav', 'aSc', 'rip', 'tis', 'awe', 'som', 'e' ]
Conclusion
This function efficiently removes spaces and splits strings into equal-sized chunks using regex for space removal and the slice method for chunking. The last chunk automatically handles any remaining characters.
