Repeating each character number of times their one based index in a string using JavaScript


Problem

We are required to write a JavaScript function that takes in a string of english lowercase alphabets.

Our function should construct a new string in which each character is repeated the number of times their 1-based index in the string in capital case and different character sets should be separated by dash ‘-’.

Therefore, the string ‘abcd’ should become −

"A-Bb-Ccc-Dddd"

Example

Following is the code −

 Live Demo

const str = 'abcd';
const repeatStrings = (str) => {
   const res = [];
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      let temp = el.repeat(i + 1);
      temp = temp[0].toUpperCase() + temp.substring(1, temp.length);
      res.push(temp);
   };
   return res.join('-');
};
console.log(repeatStrings(str));

Output

A-Bb-Ccc-Dddd

Updated on: 20-Apr-2021

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements