Duplicate Text 🔧

Duplicate the selected text by replacing a word with multiple variations, divided by a comma separator.

// Name: Duplicate Text
// Description: Duplicate the selected text by replacing a word with multiple variations, divided by a comma separator.
// Author: Eduard Uffelmann
// Linkedin: https://www.linkedin.com/in/euffelmann/
// Twitter: @schmedu_
// Website: https://schmedu.com

import "@johnlindquist/kit";

let input = await getSelectedText();

let buildPreview = ([search, replacement]) => {
    if (!search) return md(input);
    if (!replacement)
        return md(
            `${input
                .replaceAll("\n", "<br>")
                .replaceAll(search, `<ins>${search}</ins>`)}`
        );
    return md(
        `${input}
${replacement
            .split(",")
            .map((item) => {
                return input
                    .replaceAll("\n", "<br>")
                    .replaceAll(search, `<ins>${item}</ins>`);
            })
            .join("<br>")}`
    );
};

let [search, replacement] = await fields({
    fields: ["Search", "Replacement"],
    preview: buildPreview(["", ""]),
    onChange: async (input, state) => {
        let preview = buildPreview(state?.value);
        setPreview(preview);
    },
});

let result = `${input}
${replacement
        .split(",")
        .map((item) => {
            return input.replaceAll(search, `${item}`);
        })
        .join("\n")}`;

// Output
await setSelectedText(result);