How to usesubstr() Method in Javascript
- This example is using the substr() method to format a phone number in Human-Readable format.
- It is taking a substrings of length 3 and putting ‘-‘ among them. Remaining string elements using the same method.
Example: This example implements the above approach.
Javascript
const phoneNo = '4445556678' ; function formatNumber() { const formatNum = phoneNo.substr(0, 3) + '-' + phoneNo.substr(3, 3) + '-' + phoneNo.substr(6, 4); console.log(formatNum); } formatNumber(); |
Output
444-555-6678
How to format a phone number in Human-Readable using JavaScript ?
Give a phone number and the task is to format a phone number in such a way that it becomes easy to understand for humans.
There are two approaches to format the numbers which are discussed below:
- Using RegExp
- Using substr() Method