
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
Insert Character at Nth Position in String in JavaScript
We are required to write a JavaScript function that takes in a string as the first argument and a number as the second argument and a single character as the third argument, let’s call this argument char.
The number is guaranteed to be smaller than the length of the array. The function should insert the character char after every n characters in the string and return the newly formed string.
For example −
If the arguments are −
const str = 'NewDelhi'; const n = 3; const char = ' ';
Then the output string should be −
const output = 'Ne wDe lhi';
Example
Following is the code −
const str = 'NewDelhi'; const n = 3; const char = ' '; const insertAtEvery = (str = '', num = 1, char = ' ') => { str = str.split('').reverse().join(''); const regex = new RegExp('.{1,' + num + '}', 'g'); str = str.match(regex).join(char); str = str.split('').reverse().join(''); return str; }; console.log(insertAtEvery(str, n, char));
Output
Following is the output on console −
Ne wDe lhi
Advertisements