- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Breaking a string into chunks of defined length and removing spaces using JavaScript
Problem
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.
Example
Following is the code −
const num = 5; const str = 'This is an example string'; const splitString = (str = '', num = 1) => { str = str.replace(/\s/g,''); const arr = []; for(let i = 0; i < str.length; i += num){ arr.push(str.slice(i,i + num)); }; return arr; }; console.log(splitString(str, num));
Output
[ 'Thisi', 'sanex', 'ample', 'strin', 'g' ]
- Related Articles
- Removing all spaces from a string using JavaScript
- Find number of spaces in a string using JavaScript
- Removing punctuations from a string using JavaScript
- How to split sentence into blocks of fixed length without breaking words in JavaScript
- Splitting an array into chunks in JavaScript
- Finding number of spaces in a string JavaScript
- Summing numbers present in a string separated by spaces using JavaScript
- Converting any string into camel case with JavaScript removing whitespace as well
- Constructing a string of alternating 1s and 0s of desired length using JavaScript
- Removing least number of elements to convert array into increasing sequence using JavaScript
- Remove extra spaces in string JavaScript?
- Break a list into chunks of size N in Python
- Removing adjacent duplicates from a string in JavaScript
- Removing comments from array of string in JavaScript
- Reversing a string while maintaining the position of spaces in JavaScript

Advertisements