Skip to content

Instantly share code, notes, and snippets.

@qtaped
Created January 9, 2024 21:50
Show Gist options
  • Save qtaped/a03cf4edf70e41271a0e623f91129ce1 to your computer and use it in GitHub Desktop.
Save qtaped/a03cf4edf70e41271a0e623f91129ce1 to your computer and use it in GitHub Desktop.
regular expression used to insert a certain character (like a comma) at every group of three digits in a number
// reg: /\B(?=(\d{3})+(?!\d))/g
let number = "1234567890";
let formattedNumber = number.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
console.log(formattedNumber);
// return 1 234 567 890
// "/": Delimiters used to indicate the beginning and end of the regular expression.
// "\B": This is a word boundary assertion, which matches a position that is not a word boundary. In this context, it's used to ensure that the following pattern only matches within a number and not at the beginning or end.
// "(?=(\d{3})+(?!\d))": This is a positive lookahead assertion, which is a way to check if a certain pattern follows the current position without including it in the match.
// "(\d{3})+": This part matches groups of three digits. \d represents a digit, and {3} specifies that exactly three digits should be matched. The + outside the parentheses means that this group can be repeated one or more times.
// "(?!\d)": This is a negative lookahead assertion, ensuring that the three-digit group is not followed by another digit. It's a way to make sure that the match occurs at the right place in a number, without including the fourth digit.
// "/g:" This flag stands for global, and it means that the regular expression should be applied globally to the entire string, rather than stopping after the first match.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment