Skip to content

Instantly share code, notes, and snippets.

@nikolovlazar
Created January 13, 2024 18:42
Show Gist options
  • Select an option

  • Save nikolovlazar/153a71493c6821621d3a4781d529c9df to your computer and use it in GitHub Desktop.

Select an option

Save nikolovlazar/153a71493c6821621d3a4781d529c9df to your computer and use it in GitHub Desktop.

Revisions

  1. nikolovlazar created this gist Jan 13, 2024.
    48 changes: 48 additions & 0 deletions slugify.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    // 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"],
    },
    },
    },
    };