0

I can do it with this:

const mystring = 'abcdefgh' // or '00000000'
mystring.replace(/(.{3})/g, '$1 ')

But then I get abc def gh.

How to do it from the right and get ab cde fgh ?

DevonDahon
  • 7,460
  • 6
  • 69
  • 114

1 Answers1

2

Lookahead for groups of 3 characters, eventually followed by the end of the string:

const mystring = '00000000'
console.log(
  mystring.replace(/(?=(?:.{3})*$)/g, ' ')
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320