I tend to format my styles. Although you can do that following different criteria, my main criteria is aesthetic.
I creted microsoft-capitalize
; it follows Microsoft Copywriting styleguide and it’s simple and intuitive:
const capitalize = require('microsoft-capitalize')
capitalize('Microlink CDN: Global Edge Cache')
// => 'Microlink CDN: Global edge cache'
In addition, I created a alfred-title for create format titles on the fly using Alfred
Internationalization is difficult to get right at the best of times, luckily there is a well supported API for it now in most browsers.
The method Object.prototype.toLocaleString()
will format the current Number
/Date
/Object
state into an international string locale representation.
const formatDate = ((date = new Date()),
({ lang = 'en-us', month = 'short', day = 'numeric', year = 'numeric' } = {}) =>
new Date(date).toLocaleString(lang, { month, day, year }))
Using it on action
formatDate() // 'Dec 6, 2018'
formatDate(new Date()) // 'Dec 6, 2018'
The new Intl
API introduces .RelativeTimeFormat
for formatting time.
const formatTime = (
date1 = new Date(),
date2 = new Date(),
{ lang = 'en-us', unit = 'seconds', ...opts } = {}
) => new Intl.RelativeTimeFormat(lang, opts).format(date2 - date1, unit)
Although it looks promising, still it’s an early stage.
formatTime() // "in 0 seconds"
formatTime(new Date('December 17, 1995 03:24:00'), new Date('December 17, 1995 03:24:00')) // "in 0 seconds"
formatTime(new Date('December 17, 1995 03:24:00'), new Date('December 18, 1995 03:24:00')) // "in 86,400,000 seconds"
formatTime(new Date('December 17, 1995 03:24:00'), new Date('December 18, 1995 03:24:00'), { unit: 'days' }) // "in 86,400,000 days, WTF"
Unfortunatly, it hasn’t been designed for calculating time difference.
The same approach could be used for format a Number
:
const formatNumber = ({ style = 'currency', currency = 'CAD' } = {}) => (
n,
lang = 'en-US'
) => n.toLocaleString('de-DE', { style, currency })
Using it on action
const formatter = formatNumber()
const amount = 1034532
formatter(1034532) // 🇺🇸 USA
formatter(1034532, 'de-DE') // 🇩🇪 Germany
formatter(1034532, 'ar-EG') // 🇺🇪🇬 Egypt
You can use the browser for getting the user language preference
const locale = navigator.language || navigator.userLanguage || 'en-US'
That’s could be a good point to start. Next step could remember the user preference and store it associated with the user profile settings.
const listFormat = (list, { lang = 'en-us', ...opts } = {}) => new Intl.ListFormat(lang, opts).format(list)
listFormat(['Paco']) // "Paco"
listFormat(['Paco', 'Pepe']) // "Paco and Pepe"
listFormat(['Paco', 'Pepe']) // "Paco and Pepe"
listFormat(['Paco', 'Pepe'], { type: 'disjunction' }) // "Paco or Pepe"