Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
- Create an empty array
resto store the processed character groups - Loop through each character in the input string
- For each character, repeat it
(i + 1)times using therepeat()method - Capitalize the first letter using
toUpperCase()and keep the rest lowercase - Push the processed group to the result array
- 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.
