Javascript 在javascript中插入连字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6981487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert hyphens in javascript
提问by Thanos
What is the easiest way to insert hyphens in javascript?
在javascript中插入连字符的最简单方法是什么?
I have a phone number eg.1234567890
我有一个电话号码 eg.1234567890
while displaying in the front end, I have to display it as 123-456-7890 using javascript.
在前端显示时,我必须使用 javascript 将其显示为 123-456-7890。
what is the simplest and the quickest way to achieve this?
实现这一目标的最简单和最快的方法是什么?
Thanks
谢谢
回答by Jason Gennaro
Quickest way would be with some regex:
最快的方法是使用一些正则表达式:
Where n
is the number
n
号码在哪里
n.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
n.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
Example: http://jsfiddle.net/jasongennaro/yXD7g/
示例:http: //jsfiddle.net/jasongennaro/yXD7g/
var n = "1234567899";
console.log(n.replace(/(\d{3})(\d{3})(\d{4})/, "--"));
回答by GNi33
You could use the substr-function to achieve this, assumed that the hyphens are always inserted on the same position:
您可以使用 substr-function 来实现这一点,假设连字符始终插入相同的位置:
var hypString = phonestr.substr(0,3) + '-' + phonestr.substr(3, 6) + '-' + phonestr.substr(6);
回答by Felix Kling
Given this kind of input, an other way would be:
鉴于这种输入,另一种方法是:
var phone = "1234567890";
phone = phone.replace(/(\d{3})(\d{3})(\d+)/, '--');
Of course this does not work if your input changes.
当然,如果您的输入发生变化,这将不起作用。
回答by tschubach
You can create a javascript function to format the phone number. Something like this:
您可以创建一个 javascript 函数来格式化电话号码。像这样的东西:
function formatPhoneStr(o)
{
var strPhone = o.value;
if( (strPhone != null) && (strPhone.length > 0) && (strPhone.indexOf('(') == -1))
{
if (strPhone.length == 10)
{
strPhone = '(' + strPhone.substr(0,3) + ') ' + strPhone.substr(3,3) + '-' + strPhone.substr(6,4);
}
else if (strPhone.length > 10)
{
strPhone = '(' + strPhone.substr(0,3) + ') ' + strPhone.substr(3,3) + '-' + strPhone.substr(6,4) + ' x' + strPhone.substr(10);
}
o.value = strPhone;
}
}
回答by michael g
try this...
尝试这个...
<input required type="tel" maxlength="12" onKeypress="addDashesPhone(this)" name="Phone" id="Phone">
function addDashesPhone(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;
}
回答by neves
Another alternative that I believe is the cleanest one: the slice
string method.
我认为另一种选择是最干净的:slice
字符串方法。
formattedPhone = phone.slice(0,3) + '-' + phone.slice(3, 6) + '-' phone.slice(6)
The first parameter is the start position in the string, the second is the end position. As you can see above, no parameters it goes till the end of the string. A nice feature is that, like Python, negative positions count from the end of the string. This can make your code somewhat more robust:
第一个参数是字符串中的开始位置,第二个参数是结束位置。正如您在上面看到的,直到字符串的末尾都没有参数。一个很好的特性是,像 Python 一样,负数从字符串的末尾开始计数。这可以使您的代码更加健壮:
formattedPhone = phone.slice(0,3) + '-' + phone.slice(3, -4) + '-' + phone.slice(-4)
Even if you got a phone with 9 or 11 digits it will look nice.
即使你有一部 9 位或 11 位数字的手机,它看起来也不错。
回答by Benjamin McFerren
here's my solution just in case it helps someone:
这是我的解决方案,以防万一它可以帮助某人:
validatePhone: function (e) {
验证电话:功能(e){
var number = this.$el.find('#phoneNumberField').val().replace(/-/g, '');
if(number.length > 10) {
e.preventDefault();
}
if(number.length < 3) {
number = number; // just for legibility
} else if(number.length < 7) {
number = number.substring(0,3) +
'-' +
number.substring(3,6)
} else if(number.length > 6) {
number = number.substring(0,3) +
'-' +
number.substring(3,6) +
'-' +
number.substring(6,10);
}
this.$el.find('#phoneNumberField').val(number);
}
}
回答by Brian
If you're using the ASP.NET client library they have a great String.format method that provides locale formats and all kinds of fancy stuff. The method is called as you'd expect if you're familiar with .NET:
如果您使用的是 ASP.NET 客户端库,他们有一个很棒的 String.format 方法,可以提供区域设置格式和各种花哨的东西。如果您熟悉 .NET,该方法将按您预期的方式调用:
<script type="text/javascript">
var myPhone = String.format("{0}-{1}-{2}", firstThree, secondThree, lastFour);
</script>
If you're not using ASP.NET library, I'm sure you could get the rudimentary formatting done in your own implementation - obviously this would be sans localization and you should throw some error handling/checking in the mix:
如果您不使用 ASP.NET 库,我相信您可以在自己的实现中完成基本格式设置 - 显然这将是无本地化,您应该在混合中抛出一些错误处理/检查:
function format(str, arr){
for(var i = 0; i < arr.length; i++) {
var r = new RegExp("\{" + i + "\}", "g");
str = str.replace(r,arr[i]);
}
return str;
}
alert(format("{0}-{1}-{2}", [123,456,7890]));