1

I´m not very fluent in REGEX, but I have this sequence: /(.{3})/g As far as I know, this would match every 3 characters starting at the beggining of the string. How can I start from the end of string and insert a '.' (period character) between them?

Extra info: The user will input numbers and I would like it to insert a '.' after every 3 numbers. It´s a custom made Mask I´m building for a specific project.

Thanks

1252748
  • 14,597
  • 32
  • 109
  • 229
Art
  • 237
  • 4
  • 19
  • 2
    1) show a few examples of expected input and respective output. 2) show what you've tried. 3) what does it mean to insert something between "an end" that you want to "start" from. – 1252748 Aug 12 '15 at 13:27
  • "I´m not very fluent in REGEX" >> [Regular Expression Pocket Reference](http://roydukkey.com/regular-expression-pocket-reference/) – roydukkey Aug 12 '15 at 13:29
  • Sorry for not providing a example before, but @Cranio already awnsered it. Thanks for the link. – Art Aug 12 '15 at 17:47

1 Answers1

10

Try something like:

numberString.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.")

Just be sure that numberString is indeed a string, or convert it with .toString().

Explanation: This is very tricky; it will match every digit (\d) that comes before a group of three digits \d{3} or this group repeated more than once (\d{3])+ (so every multiple of three) that is not followed by another digit !\d

It uses positive lookahead (?=) and negative lookahead (?!) in order to match or exclude parts of the strings without including them into the match results.

Then it replaces the first matching group (the digit) with itself (using the backreference $1) followed by a dot.

Cranio
  • 9,647
  • 4
  • 35
  • 55
  • @WashingtonGuedes Updated my answer – Cranio Aug 12 '15 at 13:38
  • Nice one +1: _https://regex101.com/r/aD9tM9/1_ –  Aug 12 '15 at 13:41
  • Sorry for not providing a example before. But to make it work with my code I had to change it a bit: ` /(\d{3})(?=(\d{1})+(?!\d))/g, "$1." ` It worked just fine. Also thanks for the explanation e all other replies! – Art Aug 12 '15 at 17:43