【发布时间】:2018-09-13 21:16:14
【问题描述】:
使用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>
【问题讨论】:
标签: javascript html