在javascript字符串中的特定字符后插入空格
我正在做一个表单,我想屏蔽电话号码的输入。我发现的插件不适合我,因为区号可能是1或2个字符长。 我想做的是: 当用户在前两个字符后键入数字时,脚本会在keyup上插入空格,然后在下三个字符后插入空格,然后每隔四个字符插入空格。 因此,当有人键入444时,文本框中会出现44444444。在javascript字符串中的特定字符后插入空格,javascript,jquery,regex,Javascript,Jquery,Regex,我正在做一个表单,我想屏蔽电话号码的输入。我发现的插件不适合我,因为区号可能是1或2个字符长。 我想做的是: 当用户在前两个字符后键入数字时,脚本会在keyup上插入空格,然后在下三个字符后插入空格,然后每隔四个字符插入空格。 因此,当有人键入444时,文本框中会出现44444444。 我还必须检查第二组,当有人在那里输入例如1时,数字必须是:441444444 有什么解决办法吗 你试过maskedInput插件吗 我认为它能解决你的问题 希望这有帮助。干杯你试过maskedInput插件吗
我还必须检查第二组,当有人在那里输入例如1时,数字必须是:441444444
有什么解决办法吗 你试过maskedInput插件吗 我认为它能解决你的问题
希望这有帮助。干杯你试过maskedInput插件吗 我认为它能解决你的问题
希望这有帮助。干杯你可以这样做: 将此函数应用于字符串以获取所需格式:
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进行设置:
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);
});
你可以这样做: 将此函数应用于字符串以获取所需格式:
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进行设置:
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);
});
是的,我试过了,但问题是区号。使用此插件,我可以将区号屏蔽为两个或一个字符:赛斯,我试过了,但问题是区号。使用此插件,我可以将区号屏蔽为两个或一个字符:s“我也必须检查第二组,当有人在那里键入例如1时,数字必须看起来像:441444444”,这是只针对1的情况吗?”我也必须检查第二组,当有人在那里键入例如1时,数字必须看起来像:441444444“,这是只针对1的情况吗?