0

In Python I can do this:

import re
s = '123123123123'
re.sub(r"(?<=.)(?=(?:...)+$)", ",", s )
123,123,123,123

How to make the same in JavaScript?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
user299448
  • 21
  • 2
  • possible duplicate of [How to print a number with commas as thousands separators in JavaScript](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Qantas 94 Heavy Jul 11 '14 at 10:43

1 Answers1

1

No Lookbehinds in JavaScript

The question is interesting because JS has no lookbehinds. But we can do it like this:

replaced = yourString.replace(/(?!^)(?=(?:...)+$)/g, ",");

Explanation

  • The (?!^) negative lookahead is the trick to replace your lookbehind. It asserts that what follows is not the beginning of the string. And at the beginning of the string, which is a zero-width position, that fails (think of it as 0+0=0)
  • As you know, your (?=(?:...)+$ matches a position that is followed by three characters x one or more times then the end of the string, ensuring the insertion of the comma in the right spot.
zx81
  • 41,100
  • 9
  • 89
  • 105
  • zx81, any chance you could run through what this means? – Andy Jul 11 '14 at 10:46
  • @Andy, with pleasure—just added explanation. :) – zx81 Jul 11 '14 at 10:48
  • @Andy You're welcome, mate. The `(?!^`) is interesting, as the natural idea would be `(?<!^)` which of course is not possible in JS. :) – zx81 Jul 11 '14 at 10:55
  • How can I prevent triplets after float's dot? E.g. my float is 820469710077.8724. Your example give me this: `82,046,971,007,7.8,724`. – user299448 Jul 11 '14 at 10:56
  • Mmm that's a new question. :) I exactly answered the question you asked by translating your Python regex: `How to make the same in JavaScript?`, which has the same behavior on the float. I may have time to look at another question although it's getting late here. Please see next comment. – zx81 Jul 11 '14 at 10:59
  • @zx81, I can accept your answer only after a hour, because somebody else could answer me, you know? This is how SO works... – user299448 Jul 11 '14 at 11:03
  • No worries mate, you are under no obligation to accept any answer, ever. :) I was only explaining that I exactly answered the question. The new question is not good to address in the comments, we might have have another 15 comments to talk about details. Questions are free to ask and IMO it's cleaner to keep them separate. – zx81 Jul 11 '14 at 11:05