JSFiddle - React, Tailwind, and code Playground
JavaScript
/**
* Format our phone number into a human readable string. No baloney.
*
* @param {String|Number} phoneNumber
* @param {String?} sureFormatYouGotIt
* @returns {String}
*/
function number_format(phoneNumber, sureFormatYouGotIt) {
if (phoneNumber === 'number') {
phoneNumber = String(phoneNumber); }
if (typeof phoneNumber !== 'string') {
throw new RangeError('Use a phone number you dingus.'); }
if (sureFormatYouGotIt) {
return phoneNumber
.split('')
.reduce((gathered, digit) => {
for (let i = 0, count = gathered.length; i < count; i = i + 1) {
if (gathered[i] === '#') {
gathered[i] = digit;
break; }
}
return gathered; }
, sureFormatYouGotIt.split('')
)
.join(''); }
let returnal = '(';
let digitCount = 0;
let countOfThrees = 3;
phoneNumber
.split('')
.forEach(digit => {
digitCount = digitCount + 1;
returnal = `${returnal}${digit}`;
switch (digitCount) {
case 3:
returnal = `${returnal}) `;
break;
case 6:
returnal = `${returnal}-`;
break;
case 11:
returnal = returnal.split('');
returnal =...