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

We need to write a JavaScript function that takes a string of lowercase English letters and transforms it according to specific rules: each character should be repeated based on its 1-based index position, with the first letter capitalized, and character groups separated by dashes.

Problem Statement

Given a string of lowercase English alphabets, construct a new string where:

  • Each character is repeated according to its 1-based index (1st char repeated 1 time, 2nd char repeated 2 times, etc.)
  • The first letter of each repeated group is capitalized
  • Different character groups are separated by dashes ('-')

For example, the string 'abcd' should become "A-Bb-Ccc-Dddd".

Solution

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));
A-Bb-Ccc-Dddd

How It Works

The function follows these steps:

  1. Create an empty array res to store the processed character groups
  2. Loop through each character in the input string
  3. For each character, repeat it (i + 1) times using the repeat() method
  4. Capitalize the first letter using toUpperCase() and keep the rest lowercase
  5. Push the processed group to the result array
  6. Join all groups with dashes using join('-')

Alternative Implementation

Here's a more concise version using array methods:

const repeatStringsAlt = (str) => {
   return str.split('').map((char, index) => {
      const repeated = char.repeat(index + 1);
      return repeated.charAt(0).toUpperCase() + repeated.slice(1);
   }).join('-');
};

console.log(repeatStringsAlt('hello'));
H-Ee-Lll-Llll-Ooooo

Testing with Different Inputs

console.log(repeatStrings('a'));      // Single character
console.log(repeatStrings('abc'));    // Short string  
console.log(repeatStrings('test'));   // Word with repeated letters
A
A-Bb-Ccc
T-Ee-Sss-Tttt

Conclusion

This solution efficiently transforms strings by repeating characters based on their position and formatting them with capitalization and dashes. The approach uses basic string methods like repeat(), toUpperCase(), and join() to achieve the desired pattern transformation.

Updated on: 2026-03-15T23:19:00+05:30

599 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements