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

I have a form with the ability to add a zip code (zip code, for American readers), and I want to split the entry into the following format: XXX XXXX.

I use the following JS to split it into three (XXX XXX XXX), but I want it to split only the first three, and then four or more after it.

Used JavaScript:

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 not familiar with JavaScript and RegEx. Any help is appreciated.

+4
source share
2 answers

I would probably do this:

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

Note that this will discard everything that has passed after the first 7 non-whitespace characters.

+2
source

.

var format = '',
    i;

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

Source: https://habr.com/ru/post/1678472/


All Articles