I'm currently working on a calculator and for certain reasons (long story) I don't want to use the eval function.
so what I want to do is
var exp = document.form.textview.value;
//everything on the calc is displayed in a form
var a = intiger up until the + sign
Now I have no idea how to do it, I tried doing
var a = exp.charAt(0)
but that just gives me the first character, what if the number is 2 digits.
all help is appreciated and thank you for reading have a nice day, larwa
So as i understand it you're trying to find all characters up to the + sign In the example of 12324+ you want to return 12324?
I would therefore use the "split" method on the string.
var value = "12324+";
var number = value.split('+')[0];
This will split the string into an array and return the first index (the number) to the number variable
JS' parseInt
function does pretty much what you want, eg using your var names:
var a = parseInt(exp);
For a working example, see here:
$(function(){ $('#inp').keyup(function(ev){ const val = $(ev.target).val(); // this is the important part: const int = parseInt(val); console.log(int); }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="inp" /> <h3>value:</h3> <div id="out"> </div>
To get all occurrences of integers in your input string you may use
var a = exp.match(/-?\d+/g).map(s => parseInt(s))
which will return an array of all separate integers. Working example:
$(function(){ $('#inp').keyup(function(ev){ const val = $(ev.target).val(); // this is the important part: const matches = val.match(/-?\\d+/g).map(s => parseInt(s)); console.log(matches); }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="inp" /> <h3>value:</h3> <div id="out"> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.