[JavaScript] Can someone please explain this replacement function? via /r/learnprogramming


[JavaScript] Can someone please explain this replacement function?

var stock = "1 lemon, 2 cabbages, and 101 eggs"; function minusOne(match, amount, unit) { amount = Number(amount) - 1; if (amount == 1) // only one left, remove the 's' unit = unit.slice(0, unit.length - 1); else if (amount == 0) amount = "no"; return amount + " " + unit; } console.log(stock.replace(/(\d+) (\w+)/g, minusOne)); // → no lemon, 1 cabbage, and 100 eggs 

I am confused as to what line 10 is doing.

What does ".replace (/(\d+)(\w+)/g, minusOne)" do?

I thought that the function already produced the line 11 results. Why are we replacing here?

Thank you for your time. I am a beginner. Your help is appreciated.

Submitted July 15, 2017 at 12:32AM by NewbiusCoder
via reddit http://ift.tt/2utwrPh

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s