Welcome! In this unit, we have an exciting and practical task that will test your JavaScript programming skills. We will be parsing strings and making type conversions. So, let's dive into it!
Our task for the day involves creating a JavaScript function called parseAndMultiplyNumbers()
. This function is designed to accept a string as input. However, it's not just any string — the input we'll consider is a playful mix of numbers and words.
The purpose of this function is to analyze the input string, extract all the numbers, convert these numbers (currently string types) into integer data types, and then multiply all these numbers together. The final output? It's the product of all those numbers!
Here's an illustration for clarification. Given the input string "I have 2 apples and 5 oranges," our function should return the product of 2 and 5, which is 10.
The primary task is to parse the string and identify the numbers. To do that, let's create an empty string, num
, to accumulate digits and an array numbers
to collect all the numbers we find:
The next step requires iterating through the input string character by character. When we encounter a digit, we append it to our num
string. If a character isn’t a digit and isn’t empty, it means we've reached the end of a number.
