Arrow keys: ← previous · → next 35 of 37
@nodedk/format
0.2.1 stable isomorphic

format#

Text formatting and HTML/CSS template functions for server and browser code.

Install#

npm i @nodedk/format

Usage#

var { date, time, num, esc, truncate } = require('@nodedk/format')
var value = new Date(2026, 0, 15, 14, 30, 0)

console.log(date(value)) // 2026-01-15
console.log(date(value, 'datetime-local')) // 2026-01-15T14:30:00
console.log(time(value, { lang: 'en-GB', dateStyle: 'long' }))
console.log(num(1234.5, { lang: 'en-US', minimumFractionDigits: 2 }))
// 1,234.50
console.log(esc('<b>Hello</b>')) // &lt;b&gt;Hello&lt;/b&gt;
console.log(truncate('A longer title', 8)) // A longer ...

API#

html(strings, ...values)#

Use as a tagged template: html`...` . strings is the template's string array; each interpolated value follows as an argument. Returns a string synchronously.

  • Arrays are joined with newlines.
  • null, undefined, true, and false become empty strings.
  • Other values are converted to strings.
  • Text is inserted as provided; escape dynamic plain text before interpolation.
var { html } = require('@nodedk/format')

console.log(html`<p>${false}</p>`) // <p></p>
console.log(html`<p>${0}</p>`) // <p>0</p>
console.log(html`${['one', 'two']}`) // 'one\ntwo'

css(strings, ...values)#

Alias for String.raw. Interpolates values while preserving backslashes in CSS template literals.

date(value, type = 'date')#

Formats a Date, date string, or millisecond timestamp using local time. Invalid, missing, and empty values return ''.

  • date: YYYY-MM-DD.
  • datetime-local: YYYY-MM-DDTHH:mm:ss.
  • time: HH:mm:ss.
  • month: YYYY-MM.
  • week: YYYY-Www.

Unknown types use the date format.

time(value, options)#

Formats a Date or date string with Intl.DateTimeFormat. Invalid or missing dates return ''. A string options argument is a locale; an object accepts:

  • lang: locale, default 'en'.
  • format: optional string using %weekday, %year, %month, %day, %hour, %minute, and %second.
  • Remaining fields: native Intl.DateTimeFormat options, including timeZone, dateStyle, timeStyle, year, month, day, weekday, hour, minute, second, and hour12.

Choose the matching Intl fields for each format token. Missing tokens remain unchanged; an uppercase initial, such as %Month, capitalizes the value. Options are not mutated.

var { time } = require('@nodedk/format')
var value = new Date('2026-01-15T14:30:00Z')

console.log(
  time(value, {
    lang: 'en-GB',
    timeZone: 'UTC',
    day: '2-digit',
    month: 'long',
    year: 'numeric',
    format: '%day %Month %year'
  })
)
// 15 January 2026

num(value, options)#

Returns a formatted number. String values are parsed with parseFloat after removing underscores. A string options argument sets the locale; an object accepts lang (default 'en') and native Intl.NumberFormat options. Options are not mutated.

var { num } = require('@nodedk/format')

console.log(
  num('1_234.5', {
    lang: 'en-US',
    style: 'currency',
    currency: 'USD'
  })
)
// $1,234.50

console.log(num(0.25, { style: 'percent' })) // 25%

esc(value)#

Escapes &, <, >, single quotes, and double quotes for HTML. Non-string values are returned unchanged.

raw(value)#

Decodes &amp;, &lt;, &gt;, &#39;, and &quot;. Non-string values are returned unchanged.

initials(name = '')#

Returns uppercase initials from the first two whitespace-separated name parts. A single name returns one initial; empty or omitted input returns ''.

truncate(value = '', size = 32)#

Takes a string and maximum character count. Longer strings are sliced, trimmed, and suffixed with ' ...'; the suffix is additional to size. Shorter strings are returned unchanged.

slug(value)#

Converts a value to a lowercase URL slug, transliterating common accented characters, replacing separators with hyphens, and removing unsupported characters.

slug('Héllo & Wörld!') // 'hello-world'

strip(text, separator = '\n')#

Trims each line or separated segment and rejoins with the same separator.

strip('  one  \n  two  ') // 'one\ntwo'
strip(' one | two ', '|') // 'one|two'

shorten(name, max = 20)#

Trims and collapses whitespace. When the result exceeds max, abbreviates all words except the last to initials. max triggers abbreviation; it does not guarantee a maximum output length.

shorten('Ada Augusta Lovelace', 15) // 'A. A. Lovelace'

json(value)#

Returns JSON.stringify(value, null, 2) for JSON with two-space indentation.

json({ name: 'Ada' }) // '{\n  "name": "Ada"\n}'

Created by Vidar Eldøy

Tools for business systems.