- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Articles
- 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?
- Removing nth character from a string in Python program
- Insert a specified element in a specified position in JavaScript?
- Insert an element at second position in a C# List
- Python program for removing nth character from a string
- How do I split a string, breaking at a particular character in JavaScript?
- Inserting string at position x of another string using Javascript
- How to insert an item in a list at a given position in C#?
- How to insert an object in a list at a given position in Python?
- Java Program to remove a character at a specified position
- Python Pandas - Insert a new index value at a specific position
- How to insert an object in an ArrayList at a specific position in java?
- Insert the specified element at the specified position in Java CopyOnWriteArrayList
- Second most frequent character in a string - JavaScript

Advertisements