In Exercise: Build an Egg Timer, you put two step timers on one page, and Sam’s recipe box is nearly ready for the kitchen. The next job is sharing.
Sam’s friend Ayumi keeps her recipes as plain text, one recipe per line, with the name, the minutes, and the servings separated by commas. She’s sent three of them in a message. The recipe box can’t use text like that. It needs objects whose minutes and servings are numbers it can work with.
In this lesson, you’ll cut text into pieces with split(), turn Ayumi’s lines into recipe objects with real numbers in them, and glue pieces back into one string with join(). You’ll also be able to say what each call gives you, spaces and empty pieces included. Start with one line of Ayumi’s list.
Cut a Line at Its Commas
Each line of Ayumi’s list holds three values in one string, and the box needs them apart. The string method split() does that. You pass it a separator, and it cuts the string everywhere that separator appears and returns the pieces in a new array. The method discards the separators themselves.
Go to about:blank in a new tab and open the Console with Ctrl+Shift+J, or Cmd+Option+J on macOS. Keep this tab open for the whole lesson, since later entries reuse earlier names. Split the line for Ayumi’s miso soup at its commas:
> const line = "Miso soup,15,2";
undefined
> const fields = line.split(",");
undefined
> fields
(3) ['Miso soup', '15', '2']
You get three pieces and no commas. Look at the quotes around '15' and '2', though. The method split() only cuts text. It never converts anything, so every piece is a string. Add five minutes to the soup’s time to see why that matters:
> fields[1] + 5
'155'
The + glued two pieces of text together, as it does whenever one side is a string. To get a number, convert the field with Number(), as you would any text that holds a number:
> const minutes = Number(fields[1]);
undefined
> minutes + 5
20
That’s the arithmetic the box needs, so convert each numeric string from split() with Number() before you use it.