Phone Number Formatter
ReactJS
Hard
6 views
Problem Description
Build a phone input that keeps only digits and formats as you type.
Output Format
Render a React component.
Constraints
Sanitize input and format output without external libraries.
Official Solution
import React, { useMemo, useState } from 'react';
function formatPhone(digits) {
const d = digits.slice(0, 10);
const a = d.slice(0, 3);
const b = d.slice(3, 6);
const c = d.slice(6, 10);
if (d.length <= 3) return a;
if (d.length <= 6) return a + '-' + b;
return a + '-' + b + '-' + c;
}
export default function App() {
const [raw, setRaw] = useState('');
const digits = useMemo(() => raw.replace(/\\D/g, ''), [raw]);
const view = useMemo(() => formatPhone(digits), [digits]);
function onChange(e) {
setRaw(e.target.value);
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode phone</h2>
<input value={view} onChange={onChange} inputMode='numeric' placeholder='123-456-7890' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<div style={{ marginTop: 10, color: '#555' }}>Digits: {digits}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!