- 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
Segregating a string into substrings - JavaScript
We are required to write a JavaScript function that takes in a string and a number n as two arguments (the number should be such that it exactly divides the length of string) and we have to return an array of n strings of equal length.
For example −
If the string is "how" and the number is 2, our output should be −
["h", "o", "w"];
Here, every substring exactly contains −
(length of array/n) characters
And every substring is formed by taking corresponding first and last letters of the string alternatively.
Example
Following is the code −
const str = "how"; const num = 3; const segregate = (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(segregate(str, num));
Output
This will produce the following output in console −
[ 'h', 'w', 'o' ]
- Related Articles
- Separate a string with a special character sequence into a pair of substrings in JavaScript?
- Get all substrings of a string in JavaScript recursively
- Unique substrings in circular string in JavaScript
- Adding paragraph tag to substrings within a string in JavaScript
- Is the string a combination of repeated substrings in JavaScript
- Replacing Substrings in a Java String
- How to split a long string into a vector of substrings of equal sizes in R?
- Program to find split a string into the max number of unique substrings in Python
- Counting substrings of a string that contains only one distinct letter in JavaScript
- Splitting a string into parts in JavaScript
- Split string into groups - JavaScript
- Splitting string into groups – JavaScript
- Divide a string into n equal parts - JavaScript
- Splitting a string into maximum parts in JavaScript
- Find all substrings in a string using C#

Advertisements