 acbrent25
9/4/2017 - 4:50 PM

## String Calculator: The calculator will take strings in this format: Add 2 and 4 Subtract 3 from 5 Divide 6 by 2 Multiply 3 by 7 The calculat

String Calculator: The calculator will take strings in this format: Add 2 and 4 Subtract 3 from 5 Divide 6 by 2 Multiply 3 by 7 The calculator will then calculate and return the answer. You only need to handle subtract, add, divide, and multiply and use a switch statement.

``````<!DOCTYPE html>

<html lang="en-us">

<meta charset="UTF-8">

<title>Document</title>

<body>

<!-- Script -->
<script src="app.js"></script>

</body>

</html>``````
``````// String to Calculator: SOLUTION
// ==============================

// Test strings to run in our calculator.
var test1 = "Add 2 and 4";
var test2 = "Subtract 3 from 10";
var test3 = "Multiply 8 and 2";
var test4 = "Divide 30 by 3";

// Declare our string calculator function.
function stringCalculator(string) {

// Split input into individual words
// Using toLowerCase to ensure it will match what we're checking in the switch statement.
var splitString = string.toLowerCase().split(" ");

// Check to see if the array is the correct length,
// and to see if the 1st and 3rd elements in the array have numeric values.
if (splitString.length !== 4 || isNaN(parseInt(splitString)) || isNaN(parseInt(splitString))) {

// If not, tell the user that we received an invalid request.
console.log("Invalid Request Format. Try Again");
}

// Otherwise...
else {

// Check the first element in the string for a matching calculator operation.
switch (splitString) {

// If the string is 'multiply'...
case "multiply":

// multiply the numbers.
return splitString * splitString;

// If the string is "divide"...
case "divide":

// divide the first number with the second.
return splitString / splitString;

// if the string is "subtract"...
case "subtract":

// subtract the first number from the third.
return splitString - splitString;

// If the string is "add"...