Home > Back-end >  How to create regex that adds a space after every 3-4 letters?
How to create regex that adds a space after every 3-4 letters?

Time:04-06

how to create a regex that automatically adds a space after every 3-4 letters?

I currently have a regex created, but it will add a space only after adding a letter to the input:

function format(s) {
    return s.toString().replace(/\d{3,4}?(?=..)/g, "$& ");
}

console.log(format(1234567890));
console.log(format(123456789));
console.log(format(1234567));
console.log(format(123456));
console.log(format(1234));
console.log(format(123));

So the output is like this.

123 456 7890
123 456 789
123 4567
123 456
1234
123

How to rebuild this regex so that the output is like this?

123 456 789 0
123 456 789
123 456 7
123 456
123 4
123

Thank you.

CodePudding user response:

Currently, .. is requiring two characters after the match. If you want to allow one character after the match, remove one of the wildcards:

function format(s) {
    return s.toString().replace(/\d{3,4}?(?=.)/g, "$& ");
}

console.log(format(1234567890));
console.log(format(123456789));
console.log(format(1234567));
console.log(format(123456));
console.log(format(1234));
console.log(format(123));

This produces the exact output you are looking for.

CodePudding user response:

If you have only digits, you can also match 3 digits and assert a non word boundary after it using the pattern \d{3}\B

function format(s) {
  return s.toString().replace(/\d{3}\B/g, "$& ");
}
console.log(format(1234567890));
console.log(format(123456789));
console.log(format(1234567));
console.log(format(123456));
console.log(format(1234));
console.log(format(123));

  • Related