

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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
- Related Questions & Answers
- String function to replace nth occurrence of a character in a string JavaScript
- In MySQL, how can we insert a substring at the specified position in a string?
- Insert an element at second position in a C# List
- Removing nth character from a string in Python program
- Inserting string at position x of another string using Javascript
- Java Program to remove a character at a specified position
- Insert a specified element in a specified position in JavaScript?
- Python Pandas - Insert a new index value at a specific position
- Python program for removing nth character from a string
- How do I split a string, breaking at a particular character in JavaScript?
- How to insert an object in a list at a given position in Python?
- How to insert an item in a list at a given position in C#?
- Insert the specified element at the specified position in Java CopyOnWriteArrayList
- How to insert an object in an ArrayList at a specific position in java?
- Set characters at a specific position within the string in Arduino
Advertisements