
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Insert a character after every n characters in JavaScript
Insertion of a specific character after every n characters in Javascript is an easy to understand concept and gives us a better understanding about Javascript's functions.
Here n can be any whole number ranging from 1 to less than the length of the string.
In this article we will deal with a variable inputString = "abcdefghijklmnopqrstuvwxyz," and aim to append a "-" character after every 5 characters. There are several ways to accomplish this with JavaScript, which are as follows −
Making use of the slice() method
In JavaScript, the slice() function is used to extract a portion of a given string and return a new string. The method accepts two arguments: the starting and ending indexes of the substring to be extracted. The substring includes the starting index but not the terminating index.
Example
let inputString = "Tutorials Point Simply Easy Learning"; let n = 5; // specify after how many characters does the specified character have to be inserted let insertChar = "-"; let outputString = ""; for (let i = 0; i < inputString.length; i += n) { let slice = inputString.slice(i, i + n); if(slice.length==n) outputString += slice + insertChar; else outputString += slice; } console.log(outputString);
Output
Tutor-ials -Point- Simp-ly Ea-sy Le-arnin-g
Using the replace() Method with a Regular Expression
In JavaScript, the replace() method is used to replace a specific substring or a regular expression match with a new string. The method accepts two arguments: the substring or regular expression to be replaced and the new string that will replace the substring or regular expression match and this allows us to perform complex string replacements..
Example
let inputString = "Tutorials Point Simply Easy Learning"; let n = 5; let insertChar = "-"; let outputString = inputString.replace(new RegExp(`.{${n}}`, 'g'), '$&' + insertChar); console.log(outputString);
Output
Tutor-ials -Point- Simp-ly Ea-sy Le-arnin-g
Using split() and reduce()
The split() method is used for splitting a string into an array of substrings. This method takes one argument which is known as the separator. It is used to specify the point at which the string should be split.
The reduce() method is a higher-order function. It aims to process and reduce an array into a single value. This method takes in two arguments namely a callback function and an initial value which is optional. The callback function is applied to each element in the array, and the returned value of the function is passed along to the next iteration as an accumulator. The final returned value of the function is the reduced value. They can be used together to insert a character after every n characters.
Example
let inputString = "Tutorials Point Simply Easy Learning"; let n = 5; // insert a character after every 5 characters let insertChar = "-"; let outputString = inputString.split("").reduce(function(acc, val, i) { return i % n === 0 && i !== 0 ? acc + insertChar + val : acc + val; }, ""); console.log(outputString);
Output
Tutor-ials -Point- Simp-ly Ea-sy Le-arnin-g
Using substr() and concat()
The substr() method in JavaScript is used to extract a substring from a given string, starting at a specified index and continuing for a specified number of characters. The method takes two arguments: the starting index, and the number of characters to include in the substring.
The concat() method in JavaScript is used to join two or more arrays or strings together. The method takes one or more arrays or strings as arguments, and returns a new array or string that contains all the elements of the original arrays or strings.
Example
let inputString = "abcdefghijklmnopqrstuvwxyz"; let n = 5; // insert a character after every 5 characters let insertChar = "-"; let outputString = ""; for (let i = 0; i < inputString.length; i += n) { let slice = inputString.substr(i, n); if(slice.length==n) outputString = outputString.concat(slice, insertChar); else outputString = outputString.concat(slice); } console.log(outputString);
Output
abcde-fghij-klmno-pqrst-uvwxy-z
Conclusion
There are several ways to insert a character after every n characters in a string in JavaScript, such as using the slice() method in combination with a for loop, the replace() method with regular expression, split() and join() method, substr() and concat() method, etc. The specific method you choose will depend on the requirements of your use case and your personal preference for code readability and maintainability. It is good to know that all these methods have a linear time complexity O(n). Keep in mind that when working with large strings, using a more efficient method could make a significant difference in terms of performance.
- Related Articles
- Python – Insert character in each duplicate string after every K elements
- How to add / insert certain character every x characters into cells
- JavaScript Insert space after every two letters in string?
- How to truncate character vector with three dots after n characters in R?
- Check for Palindrome after every character replacement Query in C++
- Insert a character at nth position in string in JavaScript
- How to build a string with no repeating character n separate list of characters? in JavaScript
- Replacing every nth instance of characters in a string - JavaScript
- Split a URL in JavaScript after every forward slash?
- How not to match a character after repetition in Python Regex?\n\n
- Why should we use a semicolon after every function in JavaScript?
- How to replace characters except last with a mask character in JavaScript?
- How can I cut a string after X characters in JavaScript?
- Insert value in the middle of every value inside array JavaScript
- Do I need to use a semicolon after every function in JavaScript?
