简体   繁体   中英

How to format a US tel number using a foreach loop?

Using someStringArray.indexOf() logic in a forEach loop is getting tripped up when an element has duplicate numbers.

I'm trying to take a US tel number and format as (xxx)xxx-xxxx using the 10 digit number initially as a string. Then converting to an array so I can loop through it and format it.

"use strict";

let tel = 5149100499;
let telStr = tel.toString();
let ntel = telStr.split('');

ntel.forEach(char => {
  let d = ntel.indexOf(char);
  if(ntel.indexOf(char) === 0) {
      ntel.splice(d,0,"(");
  }else if(ntel.indexOf(char) === 4){
      ntel.splice(d,0,")");
  }else if(ntel.indexOf(char, 7) === 9){
      ntel.splice(d,0,"-");
  }

});

let ntelStr = ntel.join('');

  console.log(ntelStr);

Ideally the output should be: ntelStr = (514)910-0499

 var tel = 5149100499; var s = tel.toString(); s = `(${s.substring(0, 3)})${s.substring(3,6)}-${s.substring(6,10)}` console.log(s); 

You can use string#replace to convert the telephone number to the desired format.

 "use strict"; let tel = 5149100499, result = tel.toString().replace(/(\\d{3})(\\d{3})(\\d{4})/,'($1)$2-$3'); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0;} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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