Skip to content

Instantly share code, notes, and snippets.

@DragorWW
Created January 17, 2017 13:06
Show Gist options
  • Select an option

  • Save DragorWW/de69927ec528d0483ceb0a92643d7de8 to your computer and use it in GitHub Desktop.

Select an option

Save DragorWW/de69927ec528d0483ceb0a92643d7de8 to your computer and use it in GitHub Desktop.
Phone number formatter for RU number.
/**
* Форматирование номера телефона:
* 89992223355 -> +7 999 222 33 55
* @param {string} s немер телефона
* @param {boolean} [plus=true] формат +7 или 8
* @return {string} отформатированный номер телефона.
*/
export default phoneFormat = (s, plus = true) => {
const startsWith = plus ? '+7' : '8';
let phone = s.replace(/[^0-9]/g, '');
if (phone.startsWith('7') && plus) {
phone = phone.substr(1);
}
if (phone.startsWith('8')) {
phone = phone.substr(1);
}
return phone.replace(/(\d{3})(\d{3})(\d{2})(\d{2})/g, `${startsWith} ($1) $2 $3 $4`);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment