- 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
Divide a string into n equal parts - JavaScript
We are required to write a JavaScript function that takes in a string and a number n (such that n exactly divides the length of string). We need to return an array of string of length n containing n equal parts of the string.
Let’s write the code for this function −
Example
const str = 'this is a sample string'; const num = 5; const divideEqual = (str, num) => { const len = str.length / num; const creds = str.split("").reduce((acc, val) => { let { res, currInd } = acc; if(!res[currInd] || res[currInd].length < len){ res[currInd] = (res[currInd] || "") + val; }else{ res[++currInd] = val; }; return { res, currInd }; }, { res: [], currInd: 0 }); return creds.res; }; console.log(divideEqual(str, num));
Output
Following is the output in the console −
[ 'this ', 'is a ', 'sampl', 'e str', 'ing' ]
- Related Articles
- Divide a string in N equal parts in C++ Program
- Split string into equal parts JavaScript
- Java Program to divide a string in 'N' equal parts
- Splitting a string into parts in JavaScript
- Splitting a string into maximum parts in JavaScript
- All ways to divide array of strings into parts in JavaScript
- Draw an angle of measure ( 153^{circ} ) and divide it into four equal parts.
- Divide a number into two parts in C++ Program
- How to divide an unknown integer into a given number of even parts using JavaScript?
- Check if a line at 45 degree can divide the plane into two equal weight parts in C++
- Splitting number into n parts close to each other in JavaScript
- Draw a line segment of length ( 12.8 mathrm{~cm} ). Using compasses, divide it into four equal parts. Verify by actual measurement.
- Split a string in equal parts (grouper in Python)
- Divide a big number into two parts that differ by k in C++ Program
- Find the coordinates of the points which divide the line segment joining $A (-2, 2)$ and $B (2, 8)$ into four equal parts.

Advertisements