将特定字符后的空格插入javascript字符串
我正在处理表格,我想屏蔽电话号码的输入。 我找到的插件对我来说不合适,因为区号可能是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); });