I'm getting some inputs from the user and saving them in a div tag just like a calculator works, for example, a user puts 100-50+30 then I store it in div tag at and when user clicks on go button I want to show him the result which is 80.
I tried parseint and number since string contains operators like + / * these don't work
var a = document.querySelector(".output").innerHTML;
You can simply use eval, but for security reasons I would recommend removing everything from user input except for digits and permitted operators before evaluating the expression:
const input = '100-50+30 [some malicious code]'
const result = eval(input.replace(/[^0-9\+\-\*\/]/g, ''));
console.log(result)
Use eval() function
var expression = '100-50+30';
console.log(eval(expression));
The eval() function evaluates JavaScript code represented as a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Related
I am preparing calculator and I would like to have only one function, to get the result according to input value
const equals=document.getElementById("equals");
equals.addEventListener('click',()=>getResult(a));
a= symbol.innerText
function getResult(a){
result.innerText = +calculations1.innerText a +calculations2.innerText;
> }
Where a could be either +, -, %, /, *.
Do you think it is possible to do this if a is stored as a string in element.innerText to do one function depending what stays there?
I try to make my function cleaner
In my current app, I am implementing field validation with regex for forms.
More specifically, I am having trouble handling edge-case for numbers with decimals.
Essentially I am using regex to prevent users from typing wrong information in to the input fields.
For instance, if user would type 12.2 and then . afterwards, I am using regex to detect what shouldn't be there, and replace with empty string, ''
Here's my current implementation using a call back function:
export const checkFormat = (typeFormat, value) => {
//value is stringified
switch (typeFormat) {
//...
case NUMERIC_DECIMALS: {
return value.replace(/(\d+\.\d+)(\.*)\d*/g, '$1')
}
}
}
However, the current regex implementation can't handle such cases as
User types : ., then .. ==> .
User types : 123.2, then 1.23.2 ==> 1.232
I'm fairly new to Regex, so obviously it needs some work
You can try this:
^(\d+(?:\.\d+)).*$
and replace by this:
$1
Regex 101 demo
Or to get the a more complex solution, which I guess you are looking for, you may try this:
const regex = /^(\d+(?:\.\d*))|(\.)?/gm;
const str = ["1.2","...","g..g","1.23","1.2.3.4",".,",".,","123.2","1.23.2","14","1","15.6.4789756465","g"];
const replaceRegex = /[^\.\d]/gm;
for(var i=0;i<str.length;i++)
{
var res=str[i].replace(replaceRegex,'').split(regex);
var finalResult="";
var alreadyContainsDot=false;
for(var j=0;j<res.length;j++)
if(res[j]!=null && res[j]!="")
{
if(res[j].includes(".") && !alreadyContainsDot)
alreadyContainsDot=true;
else if(res[j].includes(".") && alreadyContainsDot)
res[j]=res[j].replace(/\./gm,'');
finalResult+=res[j];
}
console.log(str[i]+"==>"+finalResult);
}
If my interpretation of the requirement is correct, this should work:
const regex = /(\d+\.?\d+?)(\D+)/g;
const str = `131/1.13.ad`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Regex101 link
It is bad UX practice to monitor what the user is typing and change his input out from underneath him. He is likely to think his keyboard is broken. I don't know when or how this approach became so widespread, but thankfully it seems to be dying out.
In any case, it is always a bad idea to try to do things with numbers using regexps, which are fundamentally designed for manipulating strings. If for some reason you need to check if some string is a valid number, use numeric APIs such as !isNaN(+value).
Use the appropriate type or pattern attributes on your input fields to do validation. If that does not suffice, validate when the user presses the "Submit" button or equivalent.
My app reads excel from a user. The app will receive "Quantity and Unit" of an item.
For Example,
5pcs.
12oz.
5lb.
I would like to get the number and store it in var qu[0].
I would like to get the string and store it in var qu[1].
How can i do it? I tried split. but only the number is taken.
You can get the number with an regular expression an the following pattern:
^(\d*)(.*)$
How to use regular expressions in Javascript
alert(Number("45a".match(/\d*/)) + 1)
https://jsfiddle.net/zep0tu0b/
Use parseInt or parseFloat to extract the number.
Then the remaining part should be the unit.
var num = parseFloat(str),
unit = str.substr(num.toString().length);
Consider checking if num is NaN, and then set unit to something else.
I have a form that has a field that takes what a decimal value. The desired requirements for this decimal are that it be in the form ##.## with two numbers on each side of the decimal point.
I found a regex online that is supposed to validate the decimal, but instead views any input as invalid. Here is the code I have:
function validateDecimal(number)
{
eval("var stringvar=/^[-+]?([0-9]*\\.[0-9]{0,2})|([0-9]+)$/");
return stringvar.test(number);
}
And the call...
var numStr = document.getElementById('Amount');
if (!validateDecimal(numStr)) {
alert("Please enter a valid dollar amount in the form ##.##");
return false;
}
I understand that this regex is not exactly what I'm looking for, but I can't seem to figure out why it views all input as invalid. Does anyone know what I'm doing wrong?
The first problem is that you forgot to grab the actual value of your input:
document.getElementById('Amount').value
The second problem is eval, you don't need it here, you can write it like this:
var stringvar = /^[-+]?([0-9]*\.[0-9]{0,2})|([0-9]+)$/;
And third, here's the regex I propose if your number must always be XX.XX:
/^[+-]?\d\d\.\d\d$/
first off, you shouldn't be using eval like that, it puts unnecessary stress on the client, just do
var regex = /^[-+]?([0-9]*\\.[0-9]{0,2})|([0-9]+)$/;
return regex.test(number);
instead.
And you need to use .value after getElementById('Amount');
I have a page with some elements that are controlled by the user. One of these is a text input field, where the user is supposed to input a number. Everything works well if the user only inputs digits (EG 9000), but is the user uses comma notation (the being 9,000) javascript doesn't take the input as an integer.
How can I remove the commas and/or force the input to an integer? I tried using parseint(), but it doesn't seem to work with commas.
Use a global regular expression to replace all commas with an empty string:
var str = "12,345,678";
str = str.replace(/,/g, "");
parseInt(str, 10);
or even better
var s="jdjsghd0182.99";
var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));
Or even better, given the general unreliability of user input, use this to get rid of all non-numeric characters:
var s = "9,Ljk876";
var t = parseInt(s.replace(/[^0-9]/g, ''));
alert ("s:" + s + ", t:" + t);
maybe
parseint(ny9000withCommas.replace(/\,/g,""))
lets talk about the restriction :
you can/should allow the user to enter both 9000 & 9,000
you can check validy via REGEX.
in the server side - you should eleminate the commas and treat it as integer.