简体   繁体   English

如何仅使用JavaScript在输入字段中拆分数据?

[英]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.

相关问题 如何使用 vanilla JavaScript 从动态创建的输入字段中获取数据? - How can I get data from dynamically created input field using vanilla JavaScript? 用户使用javascript生成的输入字段,如果验证失败,如何将其数据填充回输入字段 - User generated input field using javascript, how do I populate their data back in the input field if validation fails 当有人使用javascript或jquery粘贴文本时,如何仅在输入字段中的文本开头禁用/删除空格? - How can i disable/remove white spaces only at the beginning of text inside an input field when someone paste text using javascript or jquery? 如何使用JavaScript分割字符串 - How can I split strings using javascript 如何检测使用JavaScript的输入字段? - How can I detect which input field received input using JavaScript? 如何使用JavaScript从div的输入字段中获取输入值 - How can I get my input value from input field in a div using JavaScript 如何让输入字段只接受 javaScript 中的字母? - How do I make an input field accept only letters in javaScript? 如何仅使用javascript验证带有数字的输入字段? - How to validate input field with numbers only using javascript? 如何使用 javascript 中的 split 函数拆分值以只检查第一次和最后一次出现 - How do I split a value using the split function from javascript to split checking only the first and last occurence 如何使用 JavaScript 在输入字段中输入值? - How do I input the value in input field using JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM