LeaVerou / brep

Write batch find & replace scripts that transform files with a simple human-readable syntax
13 stars 0 forks source link

Support JS replacements #18

Open LeaVerou opened 2 months ago

LeaVerou commented 2 months ago

I just tried to write a brep script to enforce Title Case and realized there is no way to uppercase anything with the current syntax (short of painfully writing out each letter as a separate replacement).

It would be great if we supported JS as a replacement format, which could be an escape hatch for things the declarative syntax doesn't (yet) do well. it could even support custom data in a data property (just like hTest) which would be immensely useful for things like key-value replacements.

As an example, this is my title case script with that syntax:

export default {
    from: /^##+ .+$/mg,
    replace: [
        {
                from: /(?<=\s)[a-z]+(?=\s|$)/g,
                data: {
                    except: "a, an, and, as, at, but, by, for, in, nor, of, on, or, the, up".split(", "),
                },
                to (word) {
                    if (this.data.except.includes(word)) {
                        return word;
                    }

                    return word.charAt(0).toUpperCase() + word.slice(1);
                }
        },
    ]
};

Note that regexp: true is not needed, since the values are actual regexps.