Skip to content

Instantly share code, notes, and snippets.

@codegaze
Created June 14, 2020 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codegaze/5d517826fd14d1697720374205247da2 to your computer and use it in GitHub Desktop.
Save codegaze/5d517826fd14d1697720374205247da2 to your computer and use it in GitHub Desktop.
TitleCase Jekyll Titles With Node
const path = require('path');
const fs = require('fs');
const directoryPath = path.join(__dirname, '_posts');
// Loop through the folder's files
fs.readdir(directoryPath, (err, files) => {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
// Loop through all files
files.forEach((filename) => {
const file = `${directoryPath}/${filename}`;
fs.readFile(file, 'utf-8', (err, data) => {
// Split the content with `---`. The second key will be what we want
const frontMatter = data.split('---');
if (frontMatter) {
// Parse the frontMatter and find the title
const [originalTitle, uselessKey, title] = frontMatter[1].match(
/(title:\s*)(.+)/im
);
// These words should not be capitalised
const smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|v.?|vs.?|via)$/i;
// Split the title by spaces
let newTitle = title
.split(' ')
// Loop through all the items
.map((item, index, array) => {
if (
// Does it belong to the smallwords
item.search(smallWords) > -1 &&
// and it's not first or last word
index !== 0 &&
index !== array.length - 1
) {
// This needs to be lowercase
return item.toLowerCase();
} else {
// Everything else should be capitalised
return item.replace(/^['A-Za-z']/, (item) => item.toUpperCase());
}
})
.join(' ');
// Replace the old title with the new one in the original content
data = data.replace(originalTitle, `title: ${newTitle}`);
fs.writeFile(file, data, (err, result) => {
if (err) console.log('something went wrong with ' + file);
console.log('Yay!');
});
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment