Arrow keys: ← previous · → next 7 of 35
@nodedk/ext
0.1.3 stable

ext#

Formatting and HTML helpers for templates and browser code.

Install#

npm i @nodedk/ext

Usage#

var { date, time, num, esc, truncate } = require('@nodedk/ext')
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#

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/ext')
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/ext')

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.

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.

isImage(name)#

Returns whether a filename ends in gif, jpg, jpeg, tiff, png, bmp, or svg, ignoring case. The check uses the extension only.

Created by Vidar Eldøy