将特定字符后的空格插入javascript字符串 [英] Insert space after certain character into javascript string
问题描述
我正在处理表单,我想屏蔽电话号码的输入。我找到的插件对我来说不合适,因为区号可能是1或2个字符长。
我想做的是以下内容:
当用户在前两个字符之后键入其数字时,脚本在keyup上插入一个空格,然后在接下来的三个之后以及之后的每四个字符之后。
所以当有人输入44444444444然后在文本框中出现44 44 444 4444.
我也必须检查第二组,当有人在那里输入例如1时,数字必须如下:44 1 444 4444
I'm working on a form and I'd like to mask the input of the phone numbers. The plugins what I found aren't okay for me since the area code could be 1 or 2 character long. What I'd like to do is the following: when the user types his number after the first two character the script inserts a space on keyup, then after the next three and later after every fourth character. So when someone types 44444444444 then in the textbox appears 44 44 444 4444. I must check the second group as well, and when someone types there for example 1, the the number must look like: 44 1 444 4444
有任何解决办法吗?
推荐答案
你可以这样做:
将此函数应用于字符串以获得所需的格式:
Which applies this function to the string to get the desired formatting:
function formatCode(str){
var result = str;
str = str.replace(/\D+/g, "");
var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/);
if(m){
result = m[1] + " ";
if(m[2]) result += m[2] + " ";
if(m[3]) result += m[3] + " ";
if(m[4]){
result += m[4].split(/(\d{4})/).join(" ");
result = result.replace(/\s+/g, " ");
}
}
return result;
}
并使用此jQuery进行设置:
And using this jQuery to set it up:
function update(obj){
var val = obj.value;
var got = formatCode(val);
if(got != val)
obj.value = got;
}
var timer;
var prev_val = "";
$('#code').keyup(function(){
clearTimeout(timer);
// when adding numbers at the end of input, update at once
// don't want to update when editing in the middle of the string or removing parts of it
// because it would move the carret location to the end of input, and make it unusable
if(this.value.indexOf(prev_val) == 0){
update(this);
prev_val = this.value;
return;
}
prev_val = this.value;
// in other cases update 1 second after the changes are done
timer = setTimeout(update, 1000, this);
});
这篇关于将特定字符后的空格插入javascript字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!