简体   繁体   中英

How can I split data in an input field using only JavaScript?

I have a form with an option to add a post code (zip code, for US readers) and I want to split the input into the following format: XXX XXXX.

I am using the following JS to split it into threes (XXX XXX XXX), but I want it to split just the first three and then four or more after it.

JavaScript currently in use:

var ecode = document.getElementById("postcode");
ecode.oninput = function() {
    var format = ecode.value.split(" ").join("");
    if (format.length > 0) {
        format = format.match(new RegExp('.{1,3}','g')).join(" ");
    }
    this.value = format;
};

I am both new to JavaScript and RegEx. Any help is greatly appreciated.

I would probably do this:

var format = ecode.value.replace(/ /g, "");
ecode.value = format.substr(0, 3) + " " + format.substr(3, 4);

Note this will discard anything past the 7 first non-whitespace characters.

You could use a replace for the first three characters.

 var format = '', i; for (i = 0; i < 10; i++) { format += 'X'; console.log(format.replace(/.../, '$& ')); } 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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