Skip to main content
Lewiz
Inspiring
February 4, 2025
Answered

replace() function parameters

  • February 4, 2025
  • 1 reply
  • 586 views

Hi everyone,

I've been using this expression and it works great, think it was created by Ukramedia but I'm not sure. It adds points to long numbers between every group of three digits.

I have a vague idea how it works, but I would love a literal 'translation' from someone experienced. This is the expression:

 

num = value; function addCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
addCommas(num)

 

I focus particularly on the the part from ".replace" onward. I  know the B has something to do with the (right-side) boundary of what follows behind it, a digit, and then there's a negation ("not followed by digit) and then the global replacement of something (must be the specific position between the three-digit groups) with a comma.

Very fuzzy summarized, as you can see. What exactly does this line of code sound like in sequential commands?

 

Correct answer Dan Ebberts

There are optional parameters you can supply to specify how many decimal places (fraction digits), so this would be like toFixed(0):

s = effect("Slider Control")("Slider").value;
s.toLocaleString("en-US",{minimumFractionDigits: 0,maximumFractionDigits: 0})

de 

1 reply

Dan Ebberts
Community Expert
Community Expert
February 4, 2025

The part between the forward slashes is a Regular Expression, which has its own cryptic syntax separate from JavaScript, which you can decode with a good RegExp reference. However, I think I'd advise switching to JavaScript's built-in number formating functionality, like this example:

s = effect("Slider Control")("Slider").value;
s.toLocaleString("en-US")
Lewiz
LewizAuthor
Inspiring
February 5, 2025

Hi Dan, thanks a lot for your reply. I wish one day I would come even close to your expertise. Trying to learn all the time though. 
I already tried that beautiful line (didn't know of it's existence until a couple of days ago) but then I ran into the limitation of not being able to add a .toFixed(0) as well, to avoid decimals. You can have one of them, either .toLocaleString or .toFixed but not both. As I couldn't figure out another workaround I choose the above mentioned mystery Java line to be able to add .toFixed later. But there must be a better solution, in combination with .toLocaleString, I think?

Oh yes, I will dive into RexExp as soon as I find a good resource. I want to understand the syntax completely. 

Dan Ebberts
Community Expert
Dan EbbertsCommunity ExpertCorrect answer
Community Expert
February 5, 2025

There are optional parameters you can supply to specify how many decimal places (fraction digits), so this would be like toFixed(0):

s = effect("Slider Control")("Slider").value;
s.toLocaleString("en-US",{minimumFractionDigits: 0,maximumFractionDigits: 0})

de