Skip to content

Instantly share code, notes, and snippets.

@gwillz gwillz/moment-tags.js
Last active Sep 27, 2018

Embed
What would you like to do?
ES6 tagged template string for inline date fomatting
/**
* This doesn't _need_ to use moment.
* It's just the library that this project is using.
* Luxon or date-fns could also drop in neatly.
*/
const moment = require('moment')
// This a bad name, as is 'format', so idk.
function inline(literals, ...parts) {
let join = '';
let locations = {};
// collecting part locations
// 'abc ${a}|fmt| abc ${b} abc'
// becomes:
// 'abc |||fmt| abc || abc||'
for (let i in literals) {
join += literals[i] + '||'; // this marks non-formatted values
locations[join.length - 2] = parts[i];
}
console.log(join)
// regex offsets will match locations, format appropriately
// matching '||' or '|||fmt|'
return join.replace(/\|\|(?:\|([^|]*)\|)?/g, (m, fmt, i) => (
moment.isMoment(locations[i])
? locations[i].format(fmt)
: (locations[i] || '')
));
}
// test
if (require.main === module) {
let m = moment(new Date());
let mm = moment(new Date(1111234567890));
let mmm = 'I am not a moment';
console.log(inline`
the date is ${m}|DD MMM YYYY|
another ${mm}|ddd|
<p>lastly ${mmm}</p>
`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.