What does +(?!\d) in regex mean?

I have also seen it as +$.

I am using

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

To convert 10000 into 10,000 etc.

I think I understand everything else:

  • (\d) - find number
  • (?=\d{3}) - if followed by 3 numbers
  • '+' - don't stop after first find
  • (?!\d) - starting from the last number?
  • /g - for the whole string
  • ,"$1," - replace number with self and comma


ANSWERS:


I think you're slightly misreading it:

  • (?=\d{3}) - if followed by 3 numbers

Note that the regexp is actually:

(?=(\d{3})+

i.e. you've missed an open paren. The entire of the following:

(\d{3})+(?!\d)

is within the (?= ... ), which is a zero-width lookahead assertion—a nice way of saying that the stuff within should follow what we've matched so far, but we don't actually consume it.

The (?!\d) says that a \d (i.e. number) should not follow, so in total:

  • (\d) find and capture a number.
  • (?=(\d{3})+(?!\d)) assert that one or more groups of three digits should follow, but they should not have yet another digit following them all.

We replace with "$1,", i.e. the first number captured and a comma.

As a result, we place commas after digits which have multiples of three digits following, which is a nice way to say we add commas as thousand separators!


?! means Negative lookahead , it is used to match something not followed by something else, in your case a digit



 MORE:


 ? What does +(?!\d) in regex mean?
 ? What does +(?!\d) in regex mean?
 ? what does `too short multibyte code string in regex` mean?
 ? what does this regex mean "[^>]*
 ? what does this regex mean "[^>]*
 ? what does this regex mean "[^>]*
 ? What does u mean in regex?
 ? What does the regex '/^$/d' mean?
 ? What does the "[^]" regex pattern mean (javascript regex)?
 ? What does the "[^][]" regex mean?