npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@lacussoft/cpf-fmt

v3.0.0

Published

Utility to format CPF (Brazilian Individual's Taxpayer ID)

Readme

cpf-fmt para JavaScript

🌎 Access documentation in English

Utilitário em JavaScript/TypeScript para formatação de CPF (Cadastro de Pessoas Físicas).

Recursos

  • Entrada flexível: aceita string ou array de strings
  • Agnóstico ao formato: remove caracteres não numéricos antes de formatar
  • Personalizável: delimitadores (ponto, hífen), mascaramento (intervalo + substituição), escape HTML, codificação de URL
  • Suporte a TypeScript: definições de tipo completas e compatível com modo estrito
  • Dependências mínimas: Sem dependências externas, apenas pacotes internos como @lacussoft/utils
  • Tratamento de erros: callback onFail configurável; uso opcional de classes de exceção específicas

Instalação

# com NPM
$ npm install --save @lacussoft/cpf-fmt

# com Bun
$ bun add @lacussoft/cpf-fmt

Início rápido

// ES Modules
import cpfFmt from '@lacussoft/cpf-fmt'

// Common JS
const cpfFmt = require('@lacussoft/cpf-fmt')

Uso básico:

const cpf = '03603568195'

cpfFmt(cpf)       // '036.035.681-95'

cpfFmt(cpf, {     // '036.***.***-**'
  hidden: true
})

cpfFmt(cpf, {     // '036035681 dv 95'
  dotKey: '',
  dashKey: ' dv '
})

Para frontends legados, inclua o build UMD (ex.: minificado) em uma tag <script>; cpfFmt fica exposto globalmente:

<script src="https://cdn.jsdelivr.net/npm/@lacussoft/cpf-fmt@latest/dist/cpf-fmt.min.js"></script>

Uso

Opções de formatação

Todas as opções são opcionais. Chaves planas (sem objetos aninhados delimiters ou hiddenRange):

| Opção | Tipo | Padrão | Descrição | |--------|------|---------|-------------| | hidden | boolean | false | Quando true, mascara os dígitos no intervalo hiddenStarthiddenEnd com hiddenKey | | hiddenKey | string | '*' | Caractere(s) usado(s) para substituir os dígitos mascarados | | hiddenStart | number | 3 | Índice inicial (0–10, inclusivo) do intervalo a ocultar | | hiddenEnd | number | 10 | Índice final (0–10, inclusivo) do intervalo a ocultar | | dotKey | string | '.' | Delimitador de ponto (ex.: em 123.456.789) | | dashKey | string | '-' | Delimitador de hífen (ex.: antes dos dígitos verificadores …-58) | | escape | boolean | false | Quando true, aplica escape a caracteres especiais HTML no resultado | | encode | boolean | false | Quando true, codifica o resultado para URL (ex.: para parâmetros de query) | | onFail | (value, exception) => string | () => '' | Callback quando o tamanho da entrada sanitizada ≠ 11; o retorno é usado como resultado |

Exemplo com todas as opções:

cpfFmt(cpf, {
  hidden: true,
  hiddenKey: '#',
  hiddenStart: 3,
  hiddenEnd: 9,
  dotKey: ' ',
  dashKey: '_-_',
  escape: true,
  encode: true,
  onFail(value, exception) {
    return String(value)
  },
})

cpfFmt (função auxiliar)

Formata uma string de CPF. Sem opções, retorna o formato padrão (ex.: 123.456.789-10). Entrada com tipo inválido (não é string nem array de strings) faz o código lançar CpfFormatterInputTypeError. Comprimento inválido (após remover caracteres não numéricos, o resultado não tem 11 dígitos) é tratado pelo callback onFail em vez de lançar exceção. É a forma mais prática de usar a biblioteca. Internamente, instancia um CpfFormatter e chama format em seguida.

  • cpfInput (string ou array de strings): Valor com 11 dígitos, bruto ou já formatado (após sanitização).
  • options (opcional): Veja opções de formatação.

CpfFormatter (classe)

Para padrões reutilizáveis, você pode criar seu próprio formatador:

import { CpfFormatter } from '@lacussoft/cpf-fmt'

const formatter = new CpfFormatter({ hidden: true, hiddenKey: '#' })

formatter.format('12345678910')                      // '123.###.###-##'
formatter.format('123.456.789-10')                   // '123.###.###-##'
formatter.format(['123', '456', '789', '10'])        // '123.###.###-##'
formatter.format('12345678910', { hidden: false })   // sobrescreve nesta chamada: '123.456.789-10'
  • constructor: new CpfFormatter(options?) — as opções são opcionais e podem ser um objeto simples ou uma instância de CpfFormatterOptions.
  • format(input, options?): input pode ser string ou string[]; as options por chamada sobrescrevem os padrões da instância apenas para aquela chamada.

API

Exportações

  • cpfFmt (padrão): (cpfInput: string | string[], options?: CpfFormatterOptionsInput) => string
  • CpfFormatter: Classe para formatar CPF com opções padrão opcionais; aceita string | string[] em format().
  • CpfFormatterOptions: Classe que armazena as opções (dotKey, dashKey, hidden, hiddenKey, hiddenStart, hiddenEnd, escape, encode, onFail). Suporta merge via construtor ou set().
  • CPF_LENGTH: 11 (constante).
  • Tipos: CpfInput, CpfFormatterOptionsInput, CpfFormatterOptionsType, OnFailCallback.

Exceções

Ao usar CpfFormatter, tipo de entrada inválido (não string, não array de strings) sempre lança exceção. Opções inválidas lançam ao construir as opções. Comprimento inválido é repassado ao onFail por padrão. Podem ocorrer:

  • CpfFormatterTypeError (base para erros de tipo)
  • CpfFormatterInputTypeError — a entrada não é string nem string[]
  • CpfFormatterInputLengthException — o comprimento da entrada sanitizada não é 11
  • CpfFormatterOptionsTypeError — uma opção tem o tipo incorreto
  • CpfFormatterOptionsHiddenRangeInvalidException — hiddenStart/hiddenEnd fora do intervalo 0..10
  • CpfFormatterOptionsForbiddenKeyCharacterException — uma opção de key contém caractere não permitido

Contribuição e suporte

Contribuições são bem-vindas! Consulte nossas Diretrizes de contribuição para detalhes. Se o projeto for útil para você, considere:

Licença

Este projeto está sob a licença MIT — veja o arquivo LICENSE para detalhes.

Changelog

Veja o CHANGELOG para a lista de alterações e histórico de versões.


Feito com ❤️ por Lacus Solutions