Skip to content

Instantly share code, notes, and snippets.

@edsonmsantos
Created October 25, 2020 16:05
Show Gist options
  • Save edsonmsantos/06005597fb93dc7cc4c4933104f43b2e to your computer and use it in GitHub Desktop.
Save edsonmsantos/06005597fb93dc7cc4c4933104f43b2e to your computer and use it in GitHub Desktop.
[Mascara telefone]
function maskPhone(phone) {
phone = numberOnly(phone);
if (phone.length < 10 || phone.length > 11) {
return phone;
}
const currentText = String(phone);
let isMobile;
isMobile = currentText.length === 11;
let adjustedText;
if (!isMobile) {
const part0 = currentText.slice(0, 2);
const part1 = currentText.slice(2, 6);
const part2 = currentText.slice(6, 10);
adjustedText = `(${part0}) ${part1}-${part2}`
} else {
const part0 = currentText.slice(0, 2);
const part1 = currentText.slice(2, 3);
const part2 = currentText.slice(3, 7);
const part3 = currentText.slice(7, 11);
adjustedText = `(${part0}) ${part1} ${part2}-${part3}`
}
return String(adjustedText);
}
function numberOnly(str) {
str = str.toString();
return str.replace(/\D/g, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment