[英]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. 我有一个表格,可以选择添加邮政编码(邮政编码,美国读者),我想将输入分为以下格式: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. 我正在使用以下JS将它分成三个(XXX XXX XXX),但是我希望它只拆分前三个然后四个或更多。
JavaScript currently in use: 目前正在使用的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 both new to JavaScript and RegEx. 我是JavaScript和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. 请注意,这将丢弃超过7个第一个非空白字符的任何内容。
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.