Intercept the corresponding number in the Js string

One, parseInt() method

The first thing that comes to mind is the parseInt method provided by js.
Example 1: Use parseInt for pure numeric strings

     var str ="20200427";
   
     var num = parseInt(str);
  
     alert(num);//20200427  结果就是我们想要的

Example 2:
If it is the beginning of a number with characters in the middle, only the beginning number of the entire string will be obtained

    var str ="2020-04-27";
   
    var num = parseInt(str);
 
    alert(num);//只有字符串中的第一个数字会被返回。这里只能截取到2020

Example 3: If there are non-digit characters in front of the string, the above method will not work

    var str ="今天是:20200427";
  
    var num = parseInt(str);
   
     alert(num);//NaN  结果什么数据也获取不到。

In the above example, NaN will pop up. The easiest way to solve this problem is: if you know the string format, remove the preceding non-characters.

Example 4: directly remove the previous string format

    var str ="今天是:20200427";
     var num = parseInt(str.substring(3).substring(0).substring(1));
     alert(num);//20200427
    结果就是正确的。并且num的类型是number。alert(typeof num)//number

Obviously, this is more troublesome. In addition, there is also a parseInt() method in the java language. As long as there are non-digits in the string passed inside, myeclipse will prompt an error. The parseInt() method in Js can pass non-digital strings, as long as the string is in front of it, it will continue to run until it stops when it encounters non-digital characters.
For example, let’s analyze the second example we saw before

 var str ="2020-04-27";
var num = parseInt(str);
alert(num);//只有字符串中的第一个数字会被返回。这里只能截取到2020
     不会报错,结果还是一样,因为系统查找到"-"时就停止了,不管后面有没有数字都不会再提取了。所以不会出现20200427的结果。Js中有很多这样的例子,比如正则不写/g,默认查找符合的第一个子字符串就跳出,并不会往下面进行。本文第三个例子出现NaN,也是这个原因,请细细体会。

Regarding the parseInt() method, there can also be a second parameter. The second parameter represents the base of the first parameter, see an example:

parseInt("11", 2); // 结果:3  如果想把一个二进制数字字符串转换成整数值,只要把第二个参数设置为 2 就可以了。

The latter parameter is not written, and it is converted in decimal by default.

The last question, what does the parse function do? What is passed between programs is a string (text type), and it must be converted to the required type when used. The parse function converts the string into the type we need, such as parseInt(), parseFloat().

2. Regular (important)

Speaking of regularity earlier. In fact, the regular processing is relatively simple, just replace the non-digit characters. example:

    var str ="2020-04-27";

    var num= str.replace(/[^0-9]/ig,"");

    alert(num);//20200427//这时就是我们想要的结果了

If necessary, please contact WeChat: hdyi1997 At the same time, please explain your intention and make progress together! ! !

Guess you like

Origin blog.csdn.net/Y_6155/article/details/105785992