简体   繁体   English

如何在 JavaScript 中的“+”号之前选择一个整数

[英]How do I select an integer before a "+" sign in JavaScript

I'm currently working on a calculator and for certain reasons (long story) I don't want to use the eval function.我目前正在研究一个计算器,由于某些原因(长篇故事),我不想使用 eval 函数。

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.但这只是给了我第一个字符,如果数字是 2 位数字怎么办。

all help is appreciated and thank you for reading have a nice day, larwa感谢所有帮助并感谢您阅读祝您有美好的一天,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?因此,据我所知,您正在尝试查找 + 号之前的所有字符 在 12324+ 的示例中,您想返回 12324?

I would therefore use the "split" method on the string.因此,我会在字符串上使用“split”方法。


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这会将字符串拆分为一个数组并将第一个索引(数字)返回给 number 变量

Recognize an integer at the beginning of your input string:识别输入字符串开头的整数:

JS' parseInt function does pretty much what you want, eg using your var names: JS 的parseInt函数几乎parseInt您的需求,例如使用您的 var 名称:

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>

Recognize all integers in your input string识别输入字符串中的所有整数

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM