Tuesday, 17 May 2016

How to convert phone number format using JavaScript like international Format.

In this Article I will explain How to convert phone number format using JavaScript like international Format. For example USA format.  Convert phone number to international format (USA) in JavaScript / jQuery convert number to phone number format with example or JavaScript phone number validation example.

To convert number to phone number / international format in JavaScript we need to write the code like as shown below.

<script type="text/javascript">
function convertphoneNo() {
var phnumber = document.getElementById('txtPhoneNumbernumber').value;
var numbers = phnumber.replace(/\D/g, ''),
char = { 0: '(', 3: ') ', 6: ' - ' };
phnumber = '';
for (var i = 0; i < numbers.length; i++) {
phnumber += (char[i] || '') + numbers[i];
}
document.getElementById('lblResult').innerHTML = phnumber;
}
</script>



If you observe above code we are getting textbox value and converting number in (xxx) xxx – xxx format.

Now we will see complete example of converting number to phone number format for that we need to write the code like as shown below

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JavaScript Convert Phone Number Example</title>
<script type="text/javascript">
function convertphoneNo() {
var phnumber = document.getElementById('txtPhoneNumbernumber').value;
var numbers = phnumber.replace(/\D/g, ''),
char = { 0: '(', 3: ') ', 6: ' - ' };
phnumber = '';
for (var i = 0; i < numbers.length; i++) {
phnumber += (char[i] || '') + numbers[i];
}
document.getElementById('lblResult').innerHTML = phnumber;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Phone Number: <input type="text" id="txtPhoneNumbernumber" value="9876543210" />
<input type="button" value="Convert" onclick="convertphoneNo()" /><br /><br />
International Phone Format : <label id="lblResult"></label>
</div>
</form>
</body>
</html>

OutPut :




No comments:

Post a Comment