Advertisement
jamestha3d

US_phone_format

Nov 18th, 2022 (edited)
1,166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const test_array = [2,1,2,5,5,5,0,1,2,3];
  2.  
  3. //using for loop
  4. function format_phone_number(array)
  5. {
  6.     let result = "";
  7.     for (i in array)
  8.     {
  9.         if (i == 0)
  10.         {
  11.             result += "(";
  12.         }
  13.         if (i == 6)
  14.         {
  15.             result += "-";
  16.         }
  17.         result += array[i];
  18.         if (i == 2)
  19.         {
  20.             result += ") "
  21.         }
  22.  
  23.     }
  24.     console.log(result);
  25.     return result;
  26. }
  27.  
  28.  
  29. //using slice and join
  30. function format_phone_number(array)
  31. {
  32.     first = array.slice(0,3);
  33.     second = array.slice(3,6);
  34.     third = array.slice(6);
  35.     result = "(" + first.join("") + ") " + second.join("") + "-" + third.join("");
  36.     return result;
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement