Commas messing with number input in Javascript

前端 未结 4 1970
半阙折子戏
半阙折子戏 2020-11-30 11:07

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

相关标签:
4条回答
  • 2020-11-30 11:19

    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.

    0 讨论(0)
  • 2020-11-30 11:39

    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);
    

    0 讨论(0)
  • 2020-11-30 11:44

    or even better

    var s="jdjsghd0182.99";
    var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));
    
    0 讨论(0)
  • 2020-11-30 11:45

    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);
    
    0 讨论(0)
提交回复
热议问题