Class: Format
Format - A collection of formatting utilities for strings, numbers, and dates.
Author
Heliomar P. Marques https://navto.me/heliomarpm
Format.abbreviateNumber
abbreviateNumber()
static abbreviateNumber: (value, options) => string;Abbreviates a number by adding a suffix based on its magnitude. The function supports numbers up to 1 decillion (1e33) and uses the following suffixes:
- K for thousand (1e3)
- M for million (1e6)
- B for billion (1e9)
- T for trillion (1e12)
- Q for quadrillion (1e15)
- Qi for quintillion (1e18)
- S for sextillion (1e21)
- Se for septillion (1e24)
- O for octillion (1e27)
- N for nonillion (1e30)
- D for decillion (1e33) *
Parameters
value
The number to abbreviate.
number | bigint
options
Options for abbreviation, including:
fractionDigits: Number of decimal places to include in the abbreviated value.removeEndZero: Whether to remove trailing zeros after the decimal point.
fractionDigits?
number = 2
removeEndZero?
boolean = true
Returns
string
A string representing the abbreviated number with a suffix.
Example
abbreviateNumber(1_500); // '1.50K'
abbreviateNumber(2_000_000); // '2.00M'
abbreviateNumber(123_456_789, {fractionDigits: 1}); // '123.5M'
abbreviateNumber(1e33, {removeEndZero: false}); // '1.00D'See
Format.currency
currency()
static currency: (value, options) => string;Formats a number as a currency string. Defaults to Brazilian Real (BRL) and Portuguese (Brazil) locale (pt-BR). eg: R$ 1.234,56
Parameters
value
number
The number to format.
options
Options for formatting. These include the locale and currency.
currency
string
locale
LocalesArgument
Returns
string
A string representing the formatted currency.
Throws
If the value is not a number.
Example
Format.currency(123456.78); // 'R$ 123.456,78'Format.currency(1234.56);
// Output: R$ 1.234,56See
https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Format.date
date()
static date: (date, format, options) => string;Formats a Date object into a string according to the specified format. Supported formats are:
- 'a': 'am' or 'pm' in lowercase
- 'A': 'AM' or 'PM' in uppercase
- 'hh': two-digit hours in 12h format (01-12)
- 'h': hours in 12h format (1-12)
- 'HH': two-digit hours in 24h format (00-23)
- 'H': hours in 24h format (0-23)
- 'mm': two-digit minutes (00-59)
- 'ss': two-digit seconds (00-59)
- 'SSS': three-digit milliseconds (000-999)
- 'yyyy': four-digit year (2024)
- 'yy': two-digit year (24)
- 'MMMM': full month name (January, February, ...)
- 'MMM': full month name abbreviated month (Jan, Feb, ...)
- 'MM': two-digit month (01-12)
- 'M': month (1-12)
- 'dddd': full weekday name (Sun, Mon, ...)
- 'ddd': abbreviated weekday name (Sun, Mon, ...)
- 'dd': two-digit day (01-31)
- 'd': day (1-31)
Parameters
date
The date to format.
string | number | Date
format
string
The desired format for the output string.
options
Options for formatting. These include:
locale: The locale to use for formatting. Defaults to "default".timeZoneUTC: Whether to use UTC time zone. Defaults to false.
locale?
LocalesArgument
timeZoneUTC?
boolean
Returns
string
The date formatted as a string.
Example
Format.date('2025-03-02', 'dddd, dd MMMM yyyy', 'en-US'); // Output: 'Sunday, 02 March 2025'See
https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Format.interpolate
interpolate()
static interpolate: (template, ...variables) => string;Interpolates a template string with the provided variables.
Parameters
template
string
The template string to interpolate.
variables
...(string | number)[]
The variables to interpolate into the template.
Returns
string
The interpolated template string.
Throws
If a placeholder index is out of range of the provided variables.
Example
interpolate('Hello, {0}!', 'World'); // 'Hello, World!'
interpolate('The sum of {0} and {1} is {2}.', 1, 2, 3); // 'The sum of 1 and 2 is 3.'Format.maskIt
maskIt()
static maskIt(
value,
maskChar?,
startIndex?,
finalIndex?): string;Masks a substring of a string with a specified character.
Parameters
value
string
The original string to mask.
maskChar?
string = "*"
startIndex?
number = 0
The starting index of the substring to mask (inclusive).
finalIndex?
number = null
The ending index of the substring to mask (exclusive). If null, masks until the end of the string.
Returns
string
The masked string.
Throws
maskChar must be a single character
Example
maskIt('1234567890', '*', 2, 5); // '12*****90'
maskIt('1234567890', '#', 3); // '123########'Format.maskItParts
maskItParts()
static maskItParts(
text,
maskChar?,
visibleChars?): string;Masks a part of a string with a specified character.
Parameters
text
string
The original string to mask.
maskChar?
string = "*"
The character to use for masking.
visibleChars?
number = 1
The number of visible characters in the masked part.
Returns
string
The masked string.
Throws
maskChar must be a single character
Example
maskItParts('Heliomar P. Marques', '*', 1); // 'H******* P. M******'
maskItParts('+55 (11) 91888-0000', '#', 1); // '+5# (1#) 9####-0###'
maskItParts('123.444.555-67', '_', 2); // '12_.44_.55_-67'Format.number
number()
static number: (value, locale) => string;Formats a number with at least two decimal places, using the specified locale.
Parameters
value
The number to format.
number | bigint
locale
LocalesArgument = "default"
The locale to use for formatting. Defaults to "default".
Returns
string
A string representing the formatted number.
Example
Format.number(123.456, "pt-BR"); // Output: "123,46"
Format.number(123.45); // Output: "123.45"
Format.number(123); // Output: "123"See
https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Format.onlyNumbers
onlyNumbers()
static onlyNumbers: (value) => string;Removes all non-numeric characters from a string.
Parameters
value
string
The string to remove non-numeric characters from.
Returns
string
The resulting string with only numeric characters.
Example
onlyNumbers('123abc'); // '123'
onlyNumbers('abc'); // ''Format.padZerosByRef
padZerosByRef()
static padZerosByRef(value, refValue): string;Pads a number with leading zeros to match the number of digits in a given maximum value.
Parameters
value
number
The number to be padded with leading zeros.
refValue
number
The reference value for determining the maximum length for adding leading zeros. eg: 90, 110, 999, 1000, etc.
Returns
string
the input number padded with leading zeros to match the number of digits in the maximum value.
Example
Format.padZerosByRef(2, 90); // '02'
Format.padZerosByRef(12, 110); // '012'Format.ptBr
ptBr
static ptBr: object;Namespace
Formatações em português brasileiro.
cep()
cep: (value, fallback?) => string;Formata um CEP.
Parameters
value
string
O valor a ser formatado.
fallback?
string = "CEP com formato incorreto!"
O valor a ser retornado caso o valor informado esteja incorreto.
Returns
string
O CEP formatado.
Example
const cep = Format.ptBr.cep('12345678'); // Output: '12345-678'cnpj()
cnpj: (value, fallback) => string;Formata um CNPJ.
Parameters
value
string
O valor a ser formatado.
fallback
string = "CNPJ com formato incorreto!"
O valor a ser retornado caso o valor informado esteja incorreto.
Returns
string
O CNPJ formatado.
Example
const cnpj = Format.ptBr.cnpj('12345678000195'); // Output: '12.345.678/0001-95'cpf()
cpf: (value, fallback) => string;Formata um CPF.
Parameters
value
string
O valor a ser formatado.
fallback
string = "CPF com formato incorreto!"
O valor a ser retornado caso o valor informado esteja incorreto.
Returns
string
O CPF formatado.
Example
const cpf = Format.ptBr.cpf('12345678909'); // Output: '123.456.789-09'telefone()
telefone: (value, defaultAreaCode, fallback) => string;Formata um número de telefone brasileiro. Se o número tiver menos de 10 dígitos, o código de área padrão será adicionado. Se o número tiver 8 ou 9 dígitos, será formatado como um número local. Se o número tiver 10 ou 11 dígitos, será formatado com o código de área.
Parameters
value
string
O valor a ser formatado. (ex. '33987654321')
defaultAreaCode
string = ""
O código de área padrão a ser usado se o número tiver menos de 10 dígitos. (ex. '33')
fallback
string = "Telefone com formato incorreto!"
O valor a ser retornado caso o valor informado esteja incorreto.
Returns
string
O número de telefone formatado.
Example
const telefone1 = Format.ptBr.telefone('33987654321'); // Output: '33 98765-4321'
const telefone2 = Format.ptBr.telefone('987654321', '11'); // Output: '11 98765-4321'
const telefone3 = Format.ptBr.telefone('87654321', '11'); // Output: '11 8765-4321'
const telefone4 = Format.ptBr.telefone('87654321'); // Output: 'Telefone está incorreto!'See
- https://en.wikipedia.org/wiki/Telephone_numbers_in_Brazil
- https://en.wikipedia.org/wiki/List_of_country_calling_codes
- https://en.wikipedia.org/wiki/Area_codes_in_Brazil
valorPorExtenso()
valorPorExtenso: (value) => string;Converte um valor em uma string escrita por extenso.
Parameters
value
O valor a ser convertido.
number | bigint
Returns
string
Uma string com o valor escrito por extenso.
Example
Format.valorPorExtenso(1000); // Output: "mil"
Format.valorPorExtenso(1000000); // Output: "um milhão"
Format.valorPorExtenso(1000000000); // Output: "um bilhão"
Format.valorPorExtenso(1000000001); // Output: "um bilhão e um"
Format.valorPorExtenso(2_000_000_000_000_000); // Output: "dois quatrilhões"Example
import { Format } from '@heliomarpm/helpers';
const cnpj = Format.ptBr.cnpj('12345678000195'); // Output: '12.345.678/0001-95'
const cpf = Format.ptBr.cpf('12345678909'); // Output: '123.456.789-09'
const cep = Format.ptBr.cep('12345678'); // Output: '12345-678'
const telefone1 = Format.ptBr.telefone('11987654321'); // Output: '(11) 98765-4321'
const telefone2 = Format.ptBr.telefone('987654321', '11'); // Output: '(11) 98765-4321'
const valorPorExtenso = Format.ptBr.valorPorExtenso(123456); // Output: 'cento e vinte e três mil quatrocentos e cinquenta e seis'ptBr
Format.slugify
slugify()
static slugify(str): string;Converts a string to a slug.
Parameters
str
string
The string to convert.
Returns
string
The slugified string.
Example
Format.slugify('Hello, world!'); // 'hello-world'Format.titleCase
titleCase()
static titleCase(name): string;Capitalizes the first letter of the full name while maintaining lowercase for specified conjunctions.
Parameters
name
string
The full name string to format.
Returns
string
The formatted name in title case.
Example
titleCase('john doe de souza'); // 'John Doe de Souza'
titleCase('maria da silva'); // 'Maria da Silva'Format.truncate
truncate()
static truncate: (text, maxLength, ellipsis?) => string;Truncates a given text to a maximum length and appends an ellipsis.
Parameters
text
string
The text to truncate.
maxLength
number
The maximum allowed length of the text.
ellipsis?
string = "..."
The string to append to the end of the truncated text.
Returns
string
The truncated text.
Throws
If maxLength is less than or equal to the length of ellipsis.
Example
truncate('Hello, world!', 5); // 'He...'
truncate('Short text', 20); // 'Short text'