简体   繁体   中英

Add comma if numbers contains 5 or 6 digits

My input field contains multiple numbers and every numbers contains 5 or 6 digts like this:

10883 500643 10886 502814

and when user keypress and if user press space I want automatically add comma (,) between them.

How can i achieve this ?! Can anyone please help me :)

This is my code so far, it will add comma only after each numbers which contains 5 digits :

JavaScript:

<script>
    <input name="CustomerNumber" id="CustomerNumber">

    $("#CustomerNumber").on('input', function () {

    $(this).val($(this).val().replace(/,/g, '').replace(/(\d{5}(?!$))/g, "$1,"));

    });
</script>

OutPut will be come like this user enter first 5 digits comma will automatic added than user enter 6 digits comma automatic added and so on :

10883,500643,10886,502814

This will add a comma after minimum 5 and max 6 digits. If number of digits are less than 5, it won't add any comma even if there's a space. And if they are more than 6 digits, it will automatically add a comma after every 6 digits.

$(this).val($(this).val().replace(/,/g, '').replace(/(\d{5,6})/g, "$1,")

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.

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