Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript error: array.substring is not a function

I'm trying to use substrings to make a phone number out of a list of 10 digits:

function createPhoneNumber(numbers) {
  var areaCode = "(" + numbers.substring(0, 4) + ")";
  var prefix = " " + numbers.substring(3, 6);
  var lineNum = "-" + numbers.substring(6);
  return areaCode + prefix + lineNum;
}

createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);

jsbin returns this error:

"error"
"TypeError: numbers.substring is not a function
    at createPhoneNumber (xupovoy.js:8:32)
    at xupovoy.js:13:1
    at https://static.jsbin.com/js/prod/runner-3.41.2.min.js:1:13926
    at https://static.jsbin.com/js/prod/runner-3.41.2.min.js:1:10855"

Writing the return as one line yields a similar result:

function createPhoneNumber(numbers) {
  return "(" + numbers.substring(0, 4) + ") " + numbers.substring(3, 6) + "-" + numbers.substring(6);
}

createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);

I think I'll also need to use .join() to solve this, but right now I just need help to get past this error so I can see the current output.

like image 435
Meredith Stafford Avatar asked May 21 '26 00:05

Meredith Stafford


1 Answers

The substring function can only be used with strings. In order to keep working with arrays, you should use slice and then remove the commas:

function createPhoneNumber(numbers) {
  var areaCode = ("(" + numbers.slice(0, 4) + ")").replace(/,/g, "");
  var prefix = (" " + numbers.slice(3, 6)).replace(/,/g, "");
  var lineNum = ("-" + numbers.slice(6)).replace(/,/g, "");
  return areaCode + prefix + lineNum;
}

Another approach could be the use of .join(''). (Thanks @nnnnnn) This way we could remove all the replaces by one .join at the beginning of the function:

function createPhoneNumber(numbers) {
  numbers = numbers.join('');
  var areaCode = "(" + numbers.substring(0, 4) + ")";
  var prefix = " " + numbers.substring(3, 6);
  var lineNum = "-" + numbers.substring(6);
  return areaCode + prefix + lineNum;
} 

The replace will search for every comma occurrence on the generated string and it will replace them by an empty string (it will basically delete them).

To learn a little more:

Slice

Replace

Substring

Join

like image 92
Bruno Santos Avatar answered May 23 '26 13:05

Bruno Santos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!