1

I'm trying to format some strings with delimiters using regex, and its almost done, but my delimiter continues to appear at end of string.

For example, I have this code:

var myString = "abcdefghi"
var result = myString.replace(/(.{1,3})(?:(?=.{3})\.(.{1,3})(?:(?=.{3}))?)?/g, '$1.');
console.log(result) // abc.def.ghi.

And I am expecting abc.def.ghi

  • You can also try [`s.replace(/.{3}\B/g, '$&.')`](https://tio.run/##y0osSyxOLsosKNEts/j/Pye1RKFYwVZBKTEpOSU1LT0jU8maCyRYlAoSLtYrSi3ISUxO1dDXqzaujXHST9dRUFdR01PXtOZKzs8rzs9J1cvJT9cAKtf8/x8A). This works with `\B` which represents a [*non word boundary*](https://stackoverflow.com/questions/4541573/what-are-non-word-boundary-in-regex-b-compared-to-word-boundary) ([regex101 demo](https://regex101.com/r/CIgj6m/1)). – bobble bubble Aug 06 '23 at 20:00
  • What should it be for `abcdefghij` ? – The fourth bird Aug 07 '23 at 09:05

1 Answers1

1

You could use this approach

var myString = "abcdefghi";
var result = myString.match(/.{1,3}/g).join(".");
console.log(result)
Peterrabbit
  • 2,166
  • 1
  • 3
  • 19