- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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' ]
Advertisements