
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace Every Nth Instance of Characters in a String - JavaScript
We are required to write a JavaScript function that takes in a string as the first argument, a number, say n, as the second argument and a character, say c, as the third argument. The function should replace the nth appearance of any character with the character provided as the third argument and return the new string.
Example
Following is the code −
const str = 'This is a sample string'; const num = 2; const char = '*'; const replaceNthAppearance = (str, num, char) => { const creds = str.split('').reduce((acc, val, ind, arr) => { let { res, map } = acc; if(!map.has(val)){ map.set(val, 1); if(num === 0){ res += char; }else{ res += val; } }else{ const freq = map.get(val); if(num - freq === 1){ res += char; }else{ res += val; }; map.set(val, freq+1); }; return { res, map }; }, { res: '', map: new Map() }); return creds.res; } console.log(replaceNthAppearance(str, num, char));
Output
Following is the output in the console −
This ***a s*mple string
Advertisements