Javascript在电话号码中破折号 [英] Javascript dashes in phone number
问题描述
我试着研究这个问题的答案,但我迷路了。我正在尝试制作一个自动在电话号码中添加短划线的搜索栏。我已经解决了这个问题。
I tried to research the answer to this question but I'm lost. I am trying to make a one search bar that automatically puts a dash in the phone number. I've solved that.
下一部分是具有挑战性的部分。我怎么能让它总是做XXX-XXX-XXXX,即使粘贴的字符是555 555 1212或555 --- 555-1212之类的东西,它只会用555-555-1212回卷数字和输出。它不应该将空格或额外的破折号计为字符。
The next part is the challenging part. How can I make it always do XXX-XXX-XXXX, even if the characters pasted were something like 555 555 1212 or 555---555-1212, where it will only reel back the number and output with 555-555-1212. It shouldn't count the spaces or extra dashes as a character.
我发现: http://www.jotform .COM /答案/ 15202-可以-I-添加脚本到我的外形是意志,自动加连字符功能于代码和-也-之间最3位区域-3位数字前缀
我通过添加以下内容稍微改了一下:
I changed it just a bit by adding:
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
<input id="input_4" class="form-textbox" maxlength="15" name="atn" size="25" onBlur='addDashes(this)' />
现在,仅当用户输入5555555555并自动将其转换为555-555-5555时,此功能才有效。我正在试图弄清楚如何采取像5-55555-5555这样的东西并将其变成555-555-5555。目前,它是5-5-555-5-5555。
Right now, this works only if the user puts 5555555555 and automatically turns it into 555-555-5555. I'm trying to figure out how to take something like 5-55555-5555 and turn it into 555-555-5555. Currently, it makes it 5-5-555-5-5555.
看到我的困境?大声笑。它不能是php或任何服务器端脚本,因为它必须能够在桌面上运行。
See my dilemma? lol. It can't be php or any server side scripting as this must be able to run on a desktop.
决议:
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.replace(/\D/g, '');
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
推荐答案
首先,删除所有字符清理输入不是数字(参考:正则表达式替换除数字以外的所有内容和小数点)
First, clean your input by deleting all chars that are not numbers (ref.: Regex to replace everything except numbers and a decimal point)
然后,你把你的破折号。
Then, you put your dashes.
function addDashes(f)
{
f_val = f.value.replace(/\D[^\.]/g, "");
f.value = f_val.slice(0,3)+"-"+f_val.slice(3,6)+"-"+f_val.slice(6);
}
这篇关于Javascript在电话号码中破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!