JavaScript Number preserve leading 0

前端 未结 3 802
盖世英雄少女心
盖世英雄少女心 2020-12-02 02:53

I have a problem, I build a very simple javascript search for postal codes. I am using JS Numbers because I want to check if the passed number (search term) is less||equal o

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 03:01

    Store and display the postcodes as strings, thus retaining the leading zeros. If you need to make a numerical comparison convert to number at the time. The easiest way to convert is with the unary plus operator:

    var strPC = "01745",
        numPC = +strPC;
    
    alert(numPC === +"01745"); // true
    
    +value >= +splitZips[0] && +value <= +splitZips[1];
    // etc.
    

    Before you start comparing you might want to ensure the entered value actually is numeric - an easy way to be sure it is a four or five digit code with or without leading zeros is with a regex:

    /^\d{4,5}$/.test(searchTerm)       // returns true or false
    

提交回复
热议问题