Breaking up a string into an array using JavaScript

I have been working on a calculator using the eval() function, which returns a string (as shown in this tutorial). For instance, it may return something like 20+30. Now, I am trying to split this string into an array of data, such as [20, 30, 50], where 20 and 30 are the operands, and 50 is the result.

So far, here's what I've attempted:

var input = document.getElementById('screen');
var result= '20+30'; // for example
var firstOperand = result.split('+', 1); // extracting the first operand

What I really need help with is converting my input value, which is a string like "20+30", into an array: myArr = [20, 30, 50].

Any assistance would be greatly appreciated!

Answer №1

Harness the power of maps and simplify!

result = '1+2+3+4+5+6+7+8+9';
a = result.split('+').map(function(x){ return parseInt(x) });
b = a;
b.push(a.reduce(function(p, c) { return p+c; }));
// b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 45]

By the way, avoid using eval(), explore the Shunting-yard algorithm instead. You can find code examples for the algorithm here on SO and on Rosettacode.

Answer №2

When creating an array with the split function, simply pass the separator as the parameter.

var myArr = result.split('-');

To complete the array, you must now add the following value:

myArr.push("100");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to create a dedicated page in Next.js using static site generation (SSG)?

The static-site generation (SSG) feature of Nextjs allows for fetching data at build time, resulting in pre-rendered pages using getStaticProps and getStaticPaths. Imagine having a blog with numerous articles that remain static, while some may be updated ...

Obtaining Google AAID Using a Mobile Browser (JavaScript)

I've been looking for information online without much success regarding this topic. I am interested in retrieving a user's Google Advertising ID (AAID) through my website when they visit using a mobile browser. I assume it could be done with som ...

Arrange objects within nested arrays by their specific properties and then add a particular object to the end of the outer array within an object containing

I have an Object containing nested Arrays of Objects that I need to sort alphabetically by the "label" property and move the object with the label "other" to the end of each Array. I have a working solution, but I'm looking for a more streamlined appr ...

Is there a way to identify all rows that have been styled using CSS in JS?

I am looking to identify the rows that have been selected through CSS using Javascript. I have attempted some approaches with code snippets gathered from various sources. Here is an example below: ... var tableRows = document.getElementsByTagName('tr ...

A step-by-step guide to implementing cron jobs in Blitz.js

Seeking guidance on cron job implementation with Blitz.js I am in need of assistance with setting up a cron job using Blitz.js. I have already carefully reviewed the Blitz.js documentation. Progress so far I have thoroughly checked the Blitz.js document. ...

Transmit the "form data" over to the AJAX request

Snippet of HTML code: <form id="custom_form" name="custom_upload" method="POST" enctype="multipart/form-data"> <label>Choose File:</label> <input id="in" name="csv_file" value="Add CSV" type="file" required /> <table class="opt ...

When attempting to utilize useReducer hooks in React, I am encountering an issue

this is my unique code snippet import React, {createContext, useContext, useReducer } from 'react'; // defining the data layer export const StateContext = createContext(); // creating a provider export const StateProvider = ({ reducer, initi ...

Using NodeJS to retrieve a string from HTML code

Below is the provided HTML code snippet: <iframe width="100%" height="166" scrolling="no" frameborder="no" src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F11111111&amp;auto_play=false &amp;show_artwork=true& ...

Validating decimals in a text field with either JavaScript or jQuery

I need to implement text field validation on the keyup event. The text field should only accept money type decimals such as: (12.23) (.23) (0.26) (5.09) (6.00) If any incorrect value is entered, it should revert back to the previous value and remove the ...

Identify the descendant of the `<li>` tag

I need help creating a interactive checklist. The idea is that when you click on an item in the list, a hidden child element should become visible. <div id="list_one"> <h2>LIST TITLE</h2> <div id="line"></div> < ...

Images mysteriously vanishing after importing the Bootstrap stylesheet

One of the features on my website is a page where, upon hovering over an image, an overlay appears with a caption. Below is the code for one such image: <div id="content"> <div class="mosaic-block fade"> <a targe ...

Warning: Potential critical dependency detected while utilizing react-pdf package

When attempting to showcase a PDF on my react application, I encountered the following warning: /node_modules/react-pdf/node_modules/pdfjs-dist/build/pdf.js Critical dependency: require function is used in a way in which dependencies cannot be static ...

Error: The callback function is no longer supported in Model.find() in Mongoose

I am having trouble retrieving all users from the database because I keep getting an error that says Model.find() no longer accepts a callback. Can someone please help me understand how to fetch data from my mongodb database? router.get('/users', ...

Is it possible to protect passwords internally via URL and AJAX?

During my time at a previous company, we had an internal website that required a password to be entered at the end of the URL in order to view it. I suspect this was done using AJAX, but I am unsure. Even if AJAX was used, I do not know how to code it myse ...

(Node Express) The style was not applied due to its MIME type ('text/html') not being a supported stylesheet MIME type, with strict MIME checking being enabled

My CSS styles are not applying because of a MIME type issue. I am using Express to serve my HTML page, but for some reason, the CSS is not being displayed correctly. I have tried various solutions, but it seems like I am missing something simple. Can someo ...

Mistakenly appearing at the top of the window instead of the bottom of the window

Utilizing Vue.js to fetch resources from a Laravel API periodically and paginate(), after retrieving the initial 10 instances, I aim to get the next 10. Here's how my method looks: scroll () { window.onscroll = () => { let bottomOf ...

Angular checkbox is not syncing with the model

I am facing an issue in my code where the input is not properly binding to the checkbox. In my controller, I have defined a member variable like this: $scope.sameOptionsOnReturn = true; And in my view, I have set up the checkbox as follows: <input ty ...

Is there a function in Puppeteer that acts like document.ready()?

Does Puppeteer have an equivalent to document.ready()? Yes, it does: page.waitForSelector(selector) With multiple elements on a single HTML page sharing the same selector, how can this function ensure that the correct page has been loaded? This function ...

Connecting Next.js to a Database: A Step-by-Step Guide

I am interested in developing an application similar to Samsung Health that will involve heavy querying on a database. I am unsure whether it would be more beneficial to create a custom server using Node.js (with Express.js) instead of using the integrate ...

Is it advisable to save the text that is utilized in a label?

My journey into web development is just beginning, and I am currently using React JS for my front end development. I have a component that dynamically renders labels based on JSON data, This is how the JSON data looks: data:{ name:"test123" ...