Insert a 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

Updated on: 10-Dec-2020

411 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements