简体   繁体   中英

Format text input value with javascript

I have an input that needs to be formated as xx.xx.xx-xxx.xx

I have the below code but until now i manage to format it as xx-xx-xx-xx-xx-xx-xx-x

Were i am i doing wrong.

Any advice will be much appreciated.

Code:

var $form = $( ".commerce-add-to-cart" );
                    var $input = $form.find(".form-item-field-extra-velden-tkm-0-field-national-reg-num-und-0-value input");

                    $input.on( "keyup", function( event ) {


                        var selection = window.getSelection().toString();
                        if ( selection !== '' ) {
                            return;
                        }

                        if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
                            return;
                        }

                        var $this = $(this);
                        var input = $this.val();
                                input = input.replace(/[\W\s\._\-]+/g, '');

                        var split = 4;
                        var chunk = [];

                        for (var i = 0, len = input.length; i < len; i += split) {
                            split = ( i >= 2 && i <= 9 ) ? 2 : 2;
                            chunk.push( input.substr( i, split ) );
                        }

                        $this.val(function() {
                            return chunk.join("-").toUpperCase();
                        });
                });

This is my approach to formating the string, it might not be the most optimal but it does the trick quite nicely.

 let inputString = '01234567890'; let splitIndex = 6; function format (value) { let firstPart = splitString(value.substring(0, splitIndex), 2).join('.'); let secondPart = splitString(value.substring(splitIndex), 3).join('.'); return [firstPart, secondPart].join('-'); } function splitString (str, n) { let arr = []; var len; for(let i = 0, len = str.length; i < len; i += n) { arr.push(str.substr(i, n)) } return arr; } let formatedInput = format(inputString); console.log(formatedInput); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

You can use a regex replace. Each of your capture groups is represented as $x and you can do there your format.

 const inputString = '01234567890'; const formatted = inputString.replace(/(\\d{2})(\\d{2})(\\d{2})(\\d{3})(\\d{2})/g, "$1.$2.$3-$4.$5"); console.log(formatted); 

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