Skip to content

Instantly share code, notes, and snippets.

@Santosl2
Last active February 24, 2025 13:38
Show Gist options
  • Select an option

  • Save Santosl2/200eac0f4298a8a2192340dc97f8a373 to your computer and use it in GitHub Desktop.

Select an option

Save Santosl2/200eac0f4298a8a2192340dc97f8a373 to your computer and use it in GitHub Desktop.
Regex
export function cnpj(value: string) {
if (!value) return value;
return value
.replace(/\D/g, "")
.replace(/^(\d{2})(\d)/g, "$1.$2")
.replace(/(\d{3})(\d)/, "$1.$2")
.replace(/(\d{3})(\d)/, "$1/$2")
.replace(/(\d{4})(\d)/, "$1-$2")
.replace(/(-\d{2})(\d+?)$/, "$1");
}
export function cpf(value: string) {
return value
.replace(/\D/g, "")
.replace(/(\d{3})(\d)/, "$1.$2")
.replace(/(\d{3})(\d)/, "$1.$2")
.replace(/(\d{3})(\d{1,2})/, "$1-$2")
.replace(/(-\d{2})\d+?$/, "$1");
}
class Formatters {
static hour(value: string) {
if (!value) return value
const formatter = value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1:$2')
.replace(/(\d{2}):(\d{2}).+/, '$1:$2')
return formatter
}
static cep(value: string) {
if (!value) return value
const formatter = value
.replace(/\D/g, '')
.replace(/^(\d{5})(\d)/g, '$1-$2')
.replace(/-(\d{3})(\d{0,})/, '-$1')
return formatter
}
static onlyNumbers(value: string) {
return value.replace(/\D/g, '')
}
static money(value: number) {
return new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL',
}).format(value)
}
}
export { Formatters }
export function phone(value: string) {
return value
.replace(/\D/g, "")
.replace(/(\d{2})(\d)/, "($1) $2")
.replace(/(\d{5})(\d{4})(\d)/, "$1-$2");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment