简体   繁体   English

如何使用 jQuery 格式化电话号码

[英]How to format a phone number with jQuery

I'm currently displaying phone numbers like 2124771000 .我目前显示的电话号码是2124771000 However, I need the number to be formatted in a more human-readable form, for example: 212-477-1000 .但是,我需要将数字格式化为更易于阅读的形式,例如: 212-477-1000 Here's my current HTML :这是我当前的HTML

<p class="phone">2124771000</p>

Simple: http://jsfiddle.net/Xxk3F/3/简单: http : //jsfiddle.net/Xxk3F/3/

$('.phone').text(function(i, text) {
    return text.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
});

Or: http://jsfiddle.net/Xxk3F/1/或: http : //jsfiddle.net/Xxk3F/1/

$('.phone').text(function(i, text) {
    return text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '$1-$2-$3');
});

Note: The .text() method cannot be used on input elements.注意: .text() 方法不能用于输入元素。 For input field text, use the .val() method.对于输入字段文本,请使用 .val() 方法。

var phone = '2124771000',
    formatted = phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)

Don't forget to ensure you are working with purely integers.不要忘记确保您使用的是纯整数。

var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
    DATA
        .replace( /[^\d]/g, '' )
        .replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
    return DATA;
});

Here's a combination of some of these answers.这是其中一些答案的组合。 This can be used for input fields.这可用于输入字段。 Deals with phone numbers that are 7 and 10 digits long.处理 7 位和 10 位数字的电话号码。

// Used to format phone number
function phoneFormatter() {
  $('.phone').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length == 7) {
      number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
    } else if (number.length == 10) {
      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
    }
    $(this).val(number)
  });
}

Live example: JSFiddle现场示例: JSFiddle

I know this doesn't directly answer the question, but when I was looking up answers this was one of the first pages I found.我知道这并不能直接回答问题,但是当我查找答案时,这是我找到的第一页。 So this answer is for anyone searching for something similar to what I was searching for.所以这个答案适用于任何正在寻找类似于我正在寻找的东西的人。

Use a library to handle phone number.使用库来处理电话号码。 Libphonenumber by Google is your best bet. Google 的Libphonenumber是您最好的选择。

// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');

// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414

I recommend to use this package by seegno.我建议通过seegno使用这个

I have provided jsfiddle link for you to format US phone numbers as (XXX) XXX-XXX我已经为您提供了 jsfiddle 链接,用于将美国电话号码格式化为 (XXX) XXX-XXX

 $('.class-name').on('keypress', function(e) {
  var key = e.charCode || e.keyCode || 0;
  var phone = $(this);
  if (phone.val().length === 0) {
    phone.val(phone.val() + '(');
  }
  // Auto-format- do not expose the mask as the user begins to type
  if (key !== 8 && key !== 9) {
    if (phone.val().length === 4) {
      phone.val(phone.val() + ')');
    }
    if (phone.val().length === 5) {
      phone.val(phone.val() + ' ');
    }
    if (phone.val().length === 9) {
      phone.val(phone.val() + '-');
    }
    if (phone.val().length >= 14) {
      phone.val(phone.val().slice(0, 13));
    }
  }

  // Allow numeric (and tab, backspace, delete) keys only
  return (key == 8 ||
    key == 9 ||
    key == 46 ||
    (key >= 48 && key <= 57) ||
    (key >= 96 && key <= 105));
})

.on('focus', function() {
  phone = $(this);

  if (phone.val().length === 0) {
    phone.val('(');
  } else {
    var val = phone.val();
    phone.val('').val(val); // Ensure cursor remains at the end
  }
})

.on('blur', function() {
  $phone = $(this);

  if ($phone.val() === '(') {
    $phone.val('');
  }
});

Live example: JSFiddle现场示例: JSFiddle

try something like this..尝试这样的事情..

jQuery.validator.addMethod("phoneValidate", function(number, element) {
    number = number.replace(/\s+/g, ""); 
    return this.optional(element) || number.length > 9 &&
        number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

$("#myform").validate({
  rules: {
    field: {
      required: true,
      phoneValidate: true
    }
  }
});

Consider libphonenumber-js ( https://github.com/halt-hammerzeit/libphonenumber-js ) which is a smaller version of the full and famous libphonenumber.考虑 libphonenumber-js ( https://github.com/halt-hammerzeit/libphonenumber-js ),它是完整和著名的 libphonenumber 的较小版本。

Quick and dirty example:快速而肮脏的例子:

$(".phone-format").keyup(function() {
// Don't reformat backspace/delete so correcting mistakes is easier
if (event.keyCode != 46 && event.keyCode != 8) {
    var val_old = $(this).val();
    var newString = new libphonenumber.asYouType('US').input(val_old);
    $(this).focus().val('').val(newString);
}
});

(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.) (如果您确实使用正则表达式来避免库下载,请避免在退格/删除时重新格式化将更容易更正拼写错误。)

An alternative solution:另一种解决方案:

 function numberWithSpaces(value, pattern) { var i = 0, phone = value.toString(); return pattern.replace(/#/g, _ => phone[i++]); } console.log(numberWithSpaces('2124771000', '###-###-####'));

Quick roll your own code:快速滚动您自己的代码:

Here is a solution modified from Cruz Nunez's solution above.这是从上面Cruz Nunez 的解决方案修改而来的解决方案

// Used to format phone number
function phoneFormatter() {
  $('.phone').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length < 7) {
      number = number.replace(/(\d{0,3})(\d{0,3})/, "($1) $2");
    } else if (number.length <= 10) {
    number = number.replace(/(\d{3})(\d{3})(\d{1,4})/, "($1) $2-$3");
    } else {
    // ignore additional digits
    number = number.replace(/(\d{3})(\d{1,3})(\d{1,4})(\d.*)/, "($1) $2-$3");
    }
    $(this).val(number)
  });
};

$(phoneFormatter);

JSFiddle JSFiddle

  • In this solution, the formatting is applied no matter how many digits the user has entered.在此解决方案中,无论用户输入了多少位数字,都会应用格式。 (In Nunes' solution, the formatting is applied only when exactly 7 or 10 digits has been entered.) (在 Nunes 的解决方案中,仅当输入了 7 位或 10 位数字时才应用格式。)

  • It requires the zip code for a 10-digit US phone number to be entered.它需要输入 10 位美国电话号码的邮政编码。

  • Both solutions, however, editing already entered digits is problematic, as typed digits always get added to the end.然而,这两种解决方案,编辑已经输入的数字都是有问题的,因为输入的数字总是被添加到最后。

  • I recommend, instead, the robust jQuery Mask Plugin code, mentioned below:相反,我推荐强大的 jQuery Mask Plugin 代码,如下所述:

Recommend jQuery Mask Plugin推荐jQuery Mask Plugin

I recommend using jQuery Mask Plugin (page has live examples), on github .我建议在 github 上使用jQuery Mask Plugin (页面有现场示例)。
These links have minimal explanations on how to use:这些链接对如何使用有最少的解释:

CDN CDN
Instead of installing/hosting the code, you can also add a link to a CDN of the script CDN Link for jQuery Mask Plugin除了安装/托管代码,您还可以添加指向脚本CDN 链接的 CDN 链接,用于 jQuery Mask 插件
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

or或者
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>

WordPress Contact Form 7: use Masks Form Fields plugin WordPress 联系表 7:使用 Masks Form Fields 插件

If you are using Contact Form 7 plugin on a WordPress site, the easiest option to control form fields is if you can simply add a class to your input field to take care of it for you.如果您在 WordPress 网站上使用 Contact Form 7 插件,控制表单字段的最简单选项是,您可以简单地向输入字段添加一个类来为您处理。
Masks Form Fields plugin is one option that makes this easy to do. Masks Form Fields 插件一种可以轻松完成此操作的选项。
I like this option, as, Internally, it embeds a minimized version of the code from jQuery Mask Plugin mentioned above.我喜欢这个选项,因为在内部,它嵌入了上面提到的jQuery Mask Plugin代码的最小化版本。

Example usage on a Contact Form 7 form:联系表 7 表单上的示例用法:

<label> Your Phone Number (required)
    [tel* customer-phone class:phone_us minlength:14 placeholder "(555) 555-5555"]
</label>

The important part here is class:phone_us .这里的重要部分是class:phone_us
Note that if you use minlength / maxlength , the length must include the mask characters, in addition to the digits.请注意,如果您使用minlength / maxlength ,则除了数字之外,长度还必须包括掩码字符。

I found this question while googling for a way to auto-format phone numbers via a jQuery plugin.我在谷歌搜索通过 jQuery 插件自动格式化电话号码的方法时发现了这个问题。 The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted.接受的答案并不适合我的需求,自最初发布以来的 6 年里发生了很多事情。 I eventually found the solution and am documenting it here for posterity.我最终找到了解决方案,并在此处记录下来以供后代使用。

Problem问题

I would like my phone number html input field to auto-format (mask) the value as the user types.我希望我的电话号码 html 输入字段在用户键入时自动格式化(屏蔽)该值。

Solution解决方案

Check out Cleave.js .查看Cleave.js It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.这是解决此问题以及许多其他数据屏蔽问题的非常强大/灵活且简单的方法。

Formatting a phone number is as easy as:格式化电话号码非常简单:

var cleave = new Cleave('.input-element', {
    phone: true,
    phoneRegionCode: 'US'
});

Input:输入:

4546644645

Code:代码:

PhoneNumber = Input.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, "($1)$2-$3");

OutPut:输出:

(454)664-4645
 $(".phoneString").text(function(i, text) {
            text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
            return text;
        });

Output :-(123) 657-8963输出:-(123) 657-8963

Following event handler should do the needful:以下事件处理程序应该做必要的事情:

$('[name=mobilePhone]').on('keyup', function(e){
                    var enteredNumberStr=this.$('[name=mobilePhone]').val(),                    
                      //Filter only numbers from the input
                      cleanedStr = (enteredNumberStr).replace(/\D/g, ''),
                      inputLength=cleanedStr.length,
                      formattedNumber=cleanedStr;                     
                                      
                      if(inputLength>3 && inputLength<7) {
                        formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,inputLength-1) ;
                      }else if (inputLength>=7 && inputLength<10) {
                          formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);                          
                      }else if(inputLength>=10) {
                          formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);                        
                      }
                      console.log(formattedNumber);
                      this.$('[name=mobilePhone]').val(formattedNumber);
            });

To expand on Cruz Nunez code and add continual formatting, plus include some international phone number formats.扩展 Cruz Nunez 代码并添加连续格式,加上一些国际电话号码格式。

    $('#phone').on('input', function() {
      var number = $(this).val().replace(/[^\d]/g, '');
      if (number.length == 3) {
        number = number.replace(/(\d{3})/, "$1-");
      } else if (number.length == 4) {
        number = number.replace(/(\d{3})(\d{1})/, "$1-$2");
      } else if (number.length == 5) {
        number = number.replace(/(\d{3})(\d{2})/, "$1-$2");
      } else if (number.length == 6) {
        number = number.replace(/(\d{3})(\d{3})/, "$1-$2-");
      } else if (number.length == 7) {
        number = number.replace(/(\d{3})(\d{3})(\d{1})/, "$1-$2-$3");
      } else if (number.length == 8) {
        number = number.replace(/(\d{4})(\d{4})/, "$1-$2");
      } else if (number.length == 9) {
        number = number.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3");
      } else if (number.length == 10) {
        number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
      } else if (number.length == 11) {
        number = number.replace(/(\d{1})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
      } else if (number.length == 12) {
        number = number.replace(/(\d{2})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
      }
      $(this).val(number);
    });

may be this will help可能这会有所帮助

var countryCode = +91;
var phone=1234567890;
phone=phone.split('').reverse().join('');//0987654321
var formatPhone=phone.substring(0,4)+'-';//0987-
phone=phone.replace(phone.substring(0,4),'');//654321
while(phone.length>0){
formatPhone=formatPhone+phone.substring(0,3)+'-';
phone=phone.replace(phone.substring(0,3),'');
}
formatPhone=countryCode+formatPhone.split('').reverse().join('');

you will get +91-123-456-7890你会得到 +91-123-456-7890

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM