Skip to content

Instantly share code, notes, and snippets.

@nikolovlazar
Created January 13, 2024 18:42
Show Gist options
  • Save nikolovlazar/153a71493c6821621d3a4781d529c9df to your computer and use it in GitHub Desktop.
Save nikolovlazar/153a71493c6821621d3a4781d529c9df to your computer and use it in GitHub Desktop.
An Obsidian QuickAdd script that renames the file/parent folder to its slugified version
// https://byby.dev/js-slugify-string
const slugify = function (str) {
return String(str)
.normalize("NFKD") // split accented characters into their base characters and diacritical marks
.replace(/[\u0300-\u036f]/g, "") // remove all the accents, which happen to be all in the \u03xx UNICODE block.
.trim() // trim leading or trailing whitespace
.toLowerCase() // convert to lowercase
.replace(/[^a-z0-9 -]/g, "") // remove non-alphanumeric characters
.replace(/\s+/g, "-") // replace spaces with hyphens
.replace(/-+/g, "-"); // remove consecutive hyphens
};
module.exports = {
entry: async function (params, settings) {
const currentFile = Object.assign({}, params.app.workspace.getActiveFile());
const type = settings.Type;
if (type === "File") {
const slug = slugify(currentFile.basename);
const newName = currentFile.path.replaceAll(currentFile.basename, slug);
await params.app.fileManager.renameFile(currentFile, newName);
} else if (type === "Folder") {
const folderName = currentFile.parent.name;
const slug = slugify(folderName);
const newName = currentFile.path.replaceAll(folderName, slug);
const newFolderName = newName.slice(0, -9);
await params.app.vault.createFolder(newFolderName);
await params.app.fileManager.renameFile(currentFile, newName);
await params.app.vault.delete(currentFile.parent, true);
}
},
settings: {
name: "Slugify",
author: "Lazar Nikolov",
options: {
Type: {
type: "dropdown",
defaultValue: "File",
options: ["File", "Folder"],
},
},
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment