How to Add Space Between Every 4 Characters in JavaScript

How to add a space after the 4th and 10th character

With the help of regular expression, you can use the given below code to achieve the desired result:

var result = "347405405655278".replace(/^(.{4})(.{6})(.*)$/, "$1 $2 $3");

Insert space after specific amount of numbers within a string

You could use String.replace() along with Array.map() to add the required space. First of all we remove all spaces from each string, then add the space at the required position.

const input = [
"A12345678",
"ABC12345678",
"1234 56 7 8",
"12 345 67 8",
"AB12345678BVC",
]

const result = input.map(v => v.replace(/\s/g,'').replace(/(\d{3})/, '$1 '));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Add a space after every character in a string JavaScript

  "Test".split("").join(" ")
// or
[..."Test"].join(" ")

Thats it. You can't do that with .join directly as that only accepts a string.



Related Topics



Leave a reply



Submit