Files
nahodka-front/src/utils/formatPhone.js
2026-08-12 23:28:35 +03:00

21 lines
944 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Форматирует строку в маску +7 (___) ___-__-__.
* Принимает любой ввод — чистит всё кроме цифр.
* Поддерживает ввод с "7" или "8" в начале (стандартный
* российский формат телефонного номера).
*
* @param {string} val — сырое значение из input
* @returns {string} — отформатированная строка
*/
export function formatPhone(val) {
const digits = val.replace(/\D/g, "");
const local = digits.startsWith("7") || digits.startsWith("8")
? digits.slice(1)
: digits;
let result = "+7";
if (local.length > 0) result += " (" + local.slice(0, 3);
if (local.length >= 3) result += ") " + local.slice(3, 6);
if (local.length >= 6) result += "-" + local.slice(6, 8);
if (local.length >= 8) result += "-" + local.slice(8, 10);
return result;
}