JavaScript Insert space after every two letters in string?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

For this, use replace() along with regular expressions.

Example

Following is the code −

var values = "JavaScriptTutorial";
var result = values.replace(/.{1,2}(?=(.{2})+$)/g, '$& ');
console.log("The actual result is=");
console.log(values);
console.log("After inserting space at nth position=")
console.log(result);

To run the above program, you need to use the below command −

node fileName.js.

Here, my file name is demo326.js

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo326.js
The actual result is=
JavaScriptTutorial
After inserting space at nth position=
Ja va Sc ri pt Tu to ri al
raja
Published on 27-Oct-2020 10:07:59
Advertisements