- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
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 −
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
Advertisements