Drill

ProblemsJavaScript › validation

Normalise a phone number

mediumvalidationJavaScript

People type phone numbers however they like. The CRM stores exactly one shape, so the importer either produces that shape or rejects the row.

normalisePhone(raw: string, countryCode: string) → string?

Solve it in the editor →

Where you start

function normalisePhone(raw, countryCode) {
  
}

Worked examples

CallResult
normalisePhone("0532 123 45 67", "90")"+905321234567"
normalisePhone("532-123-4567", "90")"+905321234567"
normalisePhone("(532) 123 45 67", "1")"+15321234567"
normalisePhone("123", "90")null

Hint

Clean, then drop the leading zero, then check the length. Three steps in that order.

Reference solution in JavaScript
function normalisePhone(raw, countryCode) {
  if (countryCode.length < 1 || countryCode.length > 3) return null;
  for (const c of countryCode) if (c < '0' || c > '9') return null;
  let d = '';
  for (const c of raw) if (c >= '0' && c <= '9') d += c;
  if (d.startsWith('0')) d = d.slice(1);
  return d.length === 10 ? '+' + countryCode + d : null;
}

The same problem in another language

More validation problems in JavaScript