Understanding (.{5}) and $1 in JavaScript replace()

I’m learning JavaScript and I’m having trouble understanding this line:

value = value.replace(/(.{5})/g, "$1 ");

I understand that replace() is being used, but I’m confused about what exactly (.{5}) and $1 mean.

For example, if:

value = "1234567890";

then the result becomes:

12345 67890

I don’t understand how JavaScript knows that it should put a space after every 5 characters.

Can someone explain this line step by step, especially:

  1. What does (.{5}) mean?

  2. What does $1 mean?

  3. What does the g mean?

  4. How does replace() produce 12345 67890?

I’m trying to understand the concept rather than just get the answer.

this is regex, in regex () is a capture group. these groups can be referenced in the replace second argument with $1 for the first group, $2 for the second and so on

for the regex, . matches anything, and {5} is a counter that make so that . is matched 5 time

end result is that the regex matches 5 characters in the capture group, those 5 characters are then referenced by $1 and a space is added after it by the replacement string

1 Like

To add to what ILM explained, since there is a global flag (g) at the end of the regular expression, all groups of 5 characters will be matched so a value of “12345678901234” will become “12345 67890 1234”.