使用 Regular Expression to reformat a US phone number in Javascript 答案中的建议代码,我尝试以典型 HTML 表单的形式输出来自用户输入的格式化电话号码。我知道用于格式化数字的函数可以正常工作,因为如果您向该函数传递显式参数,它就可以工作。所以我的想法是我的输入可能不是作为字符串输入的。但是,我尝试通过 String() 和 toString() 进行转换,但没有成功。我错过了什么吗?
要测试格式化函数,您所要做的就是创建以电话号码字符串作为值的变量,并将这些变量作为函数参数传递以代替 officePhone 和 cellPhone.
注意:您必须单击表单下方的提交按钮才能运行脚本。
function populate(){
var officePhone = document.getElementsByName("input_office_phone")[0],
cellPhone = document.getElementsByName("input_cell_phone")[0];
function formatOfficePhone(officePhoneString) {
var cleaned = ('' + officePhoneString).replace(/\D/g, '')
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
if (match) {
return match[1] + '.' + match[2] + '.' + match[3]
}
return null
}
function formatCellPhone(cellPhoneString) {
var cleaned = ('' + cellPhoneString).replace(/\D/g, '')
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
if (match) {
return match[1] + '.' + match[2] + '.' + match[3]
}
return null
}
document.getElementById("office_phone").innerHTML = formatOfficePhone(officePhone);
document.getElementById("cell_phone").innerHTML = formatCellPhone(cellPhone);
}
<!doctype html>
<html>
<body>
<strong>***INPUT***</strong><br>
<form>
Office Phone:
<input type="text" name="input_office_phone">
<br>
Cell Phone:
<input type="text" name="input_cell_phone">
<br>
<br>
<button type="button" onClick="populate()">Submit</button>
</form>
<br>
<strong>***OUTPUT***</strong><br>
<strong>office:</strong> <span id="office_phone"></span> <br>
<strong>cell:</strong> <span id="cell_phone"></span>
</body>
</html>
最佳答案
出现此问题的原因是您获取了对输入元素 input_office_phone
和 input_cell_phone
的引用,而不是其中包含的值。要解决此问题,您需要获取元素的 .value
,如下面的示例所示。
其他一些清理:
- 您有两个相同的函数来格式化两个电话号码,而不是重复使用相同的函数。我已经在下面清理了它。
- 您在
populate()
函数中声明了格式函数。理想情况下,您不希望函数嵌套在其他函数中,因此我在下面将它们分开。
希望这有帮助!
function formatPhone(number) {
var cleaned = ('' + number).replace(/\D/g, '')
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
if (match) {
return match[1] + '.' + match[2] + '.' + match[3]
}
return null
}
function populate() {
var officePhone = document.getElementsByName("input_office_phone")[0].value,
cellPhone = document.getElementsByName("input_cell_phone")[0].value;
document.getElementById("office_phone").innerHTML = formatPhone(officePhone);
document.getElementById("cell_phone").innerHTML = formatPhone(cellPhone);
}
<strong>***INPUT***</strong><br>
<form>
Office Phone:
<input type="text" name="input_office_phone">
<br> Cell Phone:
<input type="text" name="input_cell_phone">
<br>
<br>
<button type="button" onClick="populate()">Submit</button>
</form>
<br>
<strong>***OUTPUT***</strong><br>
<strong>office:</strong> <span id="office_phone"></span> <br>
<strong>cell:</strong> <span id="cell_phone"></span>
关于javascript - 电话号码 I/O 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52321908/