Cat
Cat

Reputation: 863

Javascript - TypeError: Cannot find function startsWith in object

I'm trying to write a custom function in Google Sheets to format some phone numbers.

Each cell contains numbers like this:

And I want to write a formula that outputs them like this:

I have been writing this function, but Google Sheets gives me an error:

"TypeError: Cannot find function startsWith in object 800270963. (line 2)."

function D7PHONE(phone) {
  if (phone.startsWith(4)) {
    return "0" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(8)) {
    return "1" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(3)) {
    return "1" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(7)) {
    return "(0" + str.substring(0, 1) + ") " + str.substring(3, 5) + " " + str.substring(6, 8);
  }
}

Upvotes: 1

Views: 1259

Answers (1)

Cat
Cat

Reputation: 863

As @rb612 pointed out Sheets does not support startsWith() so I made a work around using regex.

function D7PHONE(phone) {
  phone = phone.toString();
  if (/^4/.test(phone)) {
    return "0" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^8/.test(phone)) {
    return "1" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^3/.test(phone)) {
    return "1" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^7/.test(phone)) {
    return "(0" + phone.substring(0, 1) + ") " + phone.substring(1, 5) + " " + phone.substring(5, 9);
  }
}

Upvotes: 1

Related Questions