在 JavaScript 中自动格式化电话号码(不是 JQuery)



我在这篇文章中从堆栈溢出中找到了以下用于格式化 JavaScript 电话号码的代码,但它不是美国标准格式,我想要关闭后的空间'('

即以下代码给了我输出 (123(456-7890,但我想要(123( 456-7890,希望在关闭"("之后包含空格。我试过了,但没有运气。

<script type="text/javascript">
//Phone validation
var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 13;
var phonevalue1;
var phonevalue2;
var cursorposition;
function ParseForNumber1(object) {
phonevalue1 = ParseChar(object.value, zChar);
}
function ParseForNumber2(object) {
phonevalue2 = ParseChar(object.value, zChar);
}
function backspacerUP(object, e) {
if (e) {
e = e
} else {
e = window.event
}
if (e.which) {
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber1(object)
if (keycode >= 48) {
ValidatePhone(object)
}
}
function backspacerDOWN(object, e) {
if (e) {
e = e
} else {
e = window.event
}
if (e.which) {
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber2(object)
}
function GetCursorPosition() {
var t1 = phonevalue1;
var t2 = phonevalue2;
var bool = false
for (i = 0; i < t1.length; i++) {
if (t1.substring(i, 1) != t2.substring(i, 1)) {
if (!bool) {
cursorposition = i
bool = true
}
}
}
}
function ValidatePhone(object) {
var p = phonevalue1
p = p.replace(/[^d]*/gi, "")
if (p.length < 3) {
object.value = p
} else if (p.length == 3) {
pp = p;
d4 = p.indexOf('(')
d5 = p.indexOf(')')
if (d4 == -1) {
pp = "(" + pp;
}
if (d5 == -1) {
pp = pp + ")";
}
object.value = pp;
} else if (p.length > 3 && p.length < 7) {
p = "(" + p;
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ")"
p31 = p.substring(4, l30);
pp = p30 + p31;
object.value = pp;
} else if (p.length >= 7) {
p = "(" + p;
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ")"
p31 = p.substring(4, l30);
pp = p30 + p31;
l40 = pp.length;
p40 = pp.substring(0, 8);
p40 = p40 + "-"
p41 = pp.substring(8, l40);
ppp = p40 + p41;
object.value = ppp.substring(0, maxphonelength);
}
GetCursorPosition()
if (cursorposition >= 0) {
if (cursorposition == 0) {
cursorposition = 2
} else if (cursorposition <= 2) {
cursorposition = cursorposition + 1
} else if (cursorposition <= 5) {
cursorposition = cursorposition + 2
} else if (cursorposition == 6) {
cursorposition = cursorposition + 2
} else if (cursorposition == 7) {
cursorposition = cursorposition + 4
e1 = object.value.indexOf(')')
e2 = object.value.indexOf('-')
if (e1 > -1 && e2 > -1) {
if (e2 - e1 == 4) {
cursorposition = cursorposition - 1
}
}
} else if (cursorposition < 11) {
cursorposition = cursorposition + 3
} else if (cursorposition == 11) {
cursorposition = cursorposition + 1
} else if (cursorposition >= 12) {
cursorposition = cursorposition
}
var txtRange = object.createTextRange();
txtRange.moveStart("character", cursorposition);
txtRange.moveEnd("character", cursorposition - object.value.length);
txtRange.select();
}
}
function ParseChar(sStr, sChar) {
if (sChar.length == null) {
zChar = new Array(sChar);
}
else zChar = sChar;
for (i = 0; i < zChar.length; i++) {
sNewStr = "";
var iStart = 0;
var iEnd = sStr.indexOf(sChar[i]);
while (iEnd != -1) {
sNewStr += sStr.substring(iStart, iEnd);
iStart = iEnd + 1;
iEnd = sStr.indexOf(sChar[i], iStart);
}
sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);
sStr = sNewStr;
}
return sNewStr;
}
</script>

我正在尝试在多个手机文本框中使用此功能,所有这些都在asp:Textbox

.

要在右大括号"("之后插入空格,请使用以下技巧:

function markSpace(field) {
if (field.value.includes(")")) {
field.value = field.value.split(')').join(') ');
}
if (field.value.includes(") ")) {
field.value = field.value.replace(/  +/g, ' ');
}
}

并将上述函数调用为onblur="markSpace(this);"

或者,这将是您的问题的简短而有效的答案

JavaScript代码:

window.addFormat = function addFormat(f) {
var r = /(D+)/g,
npa = '',
nxx = '',
last4 = '';
f.value = f.value.replace(r, '');
npa = f.value.substr(0, 3);
nxx = f.value.substr(3, 3);
last4 = f.value.substr(6, 4);
f.value = '(' + npa + ') ' + nxx + '-' + last4;
}

asp:Textbox

<asp:TextBox MaxLength="14" 
runat="server" 
ID="txtPhone"  
placeholder="(xxx) xxx-xxxx" 
onKeyup='addFormat(this)'/>

参考:此堆栈溢出帖子

这是一个函数来做到这一点

function formatPhone(__phone){      
var pt = /[()- ]+/gi
__phone = __phone.replace(pt, '');
__phone = '('+__phone.substr(0,3)+') '+__phone.substr(2,3)+'-'+__phone.substr(6,4);
return __phone;
}

在我看来,代码过于复杂。您应该提供一个仅数字输入(也可以 + (,然后在输入下方显示结果,以便用户看到它的格式。目录:

<input type="number" id="phone">
<p id="showphone">enter a number above</p>

和 js:

window.addEventListener("load",function(){
var phone = document.getElementById("phone");
var showphone = document.getElementById("showphone");
phone.oninput = function(){
var result = phone.value.split("");
result.splice(0,0,"(")
result.splice(4,0,") ")
result.splice(8,0," - ");
showphone.textContent = result.join("");
};
});

在行动中

如果只想在必要时显示这些格式,请执行以下操作:

if(result.length > 3 ) result.splice(4,0,"(")

你可能从这里得到一些线索。

let testNumber = "(123-12)3-1234";
function formatPhoneNumber(num) {
const number = num.match(/d/g, "");
const joinedNumber = number.join("");
console.log(joinedNumber);
const regex = /^(d{3})(d{3})(d{4})$/;
const final = joinedNumber.replace(regex, "($1)$2-$3");
return final;
console.log(final);
}
formatPhoneNumber(testNumber);
// print on console: (123)123-1234

我把console.log放进去,这样你就可以想象发生了什么。
0.testNumber的格式无关紧要,但需要是10位数字(因为const regex(
1.const number返回一个数组,每个数字都作为元素。
2.const joinedNumber返回一个数字,表示所有元素都附加了 (1231231234(
3。const regex制作零件,以便您以后可以使用 replace//(( = 零件进行控制,因此您可以看到有 3 个零件。您可以根据需要更改regex格式
4.最后,joinedNumber.replace(regex, "($1)$2-$3)将返回(123(123-1234
5.您可以更改"($1)$2-$3部分以制作所需的格式。

希望对您有所帮助。

最新更新