我正在处理一个表单,我想屏蔽电话号码的输入。我发现的插件不适合我,因为区号可能是 1 或 2 个字符长。 我想做的是以下内容: 当用户在前两个字符后键入号码时,脚本会在键盘上插入一个空格,然后在接下来的三个字符之后以及每四个字符之后插入一个空格。 因此,当有人输入 44444444444 时,文本框中会出现 44 44 444 4444。 我还必须检查第二组,当有人在那里输入例如 1 时,数字必须如下所示: 44 1 444 4444
有什么解决办法吗?
最佳答案
你可以这样做:
将此函数应用于字符串以获得所需的格式:
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);
});
关于javascript - 在 JavaScript 字符串中的某个字符后插入空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6579584/