나는 현재와 같은 전화 번호를 표시하고 2124771000있습니다. 그러나 번호를보다 사람이 읽을 수있는 형식으로 지정해야합니다 (예 : 212-477-1000. 내 현재는 다음과 같습니다 HTML.
<p class="phone">2124771000</p>
나는 현재와 같은 전화 번호를 표시하고 2124771000있습니다. 그러나 번호를보다 사람이 읽을 수있는 형식으로 지정해야합니다 (예 : 212-477-1000. 내 현재는 다음과 같습니다 HTML.
<p class="phone">2124771000</p>
답변:
단순 : http://jsfiddle.net/Xxk3F/3/
$('.phone').text(function(i, text) {
return text.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
});
또는 : 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');
});
참고 : .text () 메서드는 입력 요소에 사용할 수 없습니다. 입력 필드 텍스트의 경우 .val () 메서드를 사용합니다.
/(\d{3})?(\d{3})(\d{4})$/지역 코드가없는 경우 정규식 (사용자 지정 바꾸기 기능이 필요하지만)이 좀 더 강력 합니다
$('#x_phone').on('keypress blur',function() { var ph = $(this).val(); var temp = ph.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'); $(this).val(temp); //alert(temp); });
var phone = '2124771000',
formatted = phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)
다음은 이러한 답변 중 일부의 조합입니다. 입력 필드에 사용할 수 있습니다. 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)
});
}
라이브 예제 : JSFiddle
나는 이것이 질문에 직접 답하지 않는다는 것을 알고 있지만, 답을 찾을 때 이것은 내가 찾은 첫 페이지 중 하나였습니다. 그래서이 대답은 내가 찾던 것과 비슷한 것을 찾는 사람을위한 것입니다.
도서관을 이용하여 전화 번호를 처리하십시오. 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
나는 seegno 의이 패키지 를 사용하는 것이 좋습니다 .
미국 전화 번호 형식을 (XXX) XXX-XXX로 지정할 수 있도록 jsfiddle 링크를 제공했습니다.
$('.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('');
}
});
라이브 예제 : JSFiddle
이렇게 해봐 ..
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
}
}
});
유명한 전체 libphonenumber의 더 작은 버전 인 libphonenumber-js ( https://github.com/halt-hammerzeit/libphonenumber-js )를 고려하십시오 .
빠르고 더러운 예 :
$(".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);
}
});
(라이브러리 다운로드를 피하기 위해 정규식을 사용하는 경우 백 스페이스 / 삭제시 재 형식화를 피하면 오타를 더 쉽게 수정할 수 있습니다.)
jQuery 플러그인을 통해 전화 번호를 자동 형식화하는 방법을 검색하는 동안이 질문을 찾았습니다. 받아 들여진 답변은 내 요구에 이상적이지 않았으며 원래 게시 된 이후 6 년 동안 많은 일이 발생했습니다. 나는 결국 해결책을 찾았고 후손을 위해 여기에 문서화하고 있습니다.
문제
내 전화 번호 html 입력 필드가 사용자가 입력 할 때 값을 자동 형식 (마스킹)하도록하고 싶습니다.
해결책
Cleave.js를 확인하십시오 . 이 문제 및 기타 많은 데이터 마스킹 문제를 해결하는 매우 강력하고 유연하며 쉬운 방법입니다.
전화 번호 형식 지정은 다음과 같이 쉽습니다.
var cleave = new Cleave('.input-element', {
phone: true,
phoneRegionCode: 'US'
});
이것이 도움이 될 수 있습니다
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('');
+ 91-123-456-7890을 받게됩니다.