sinedied / devto-cli

Dev.to authoring CLI to create and publish markdown files as articles, using assets hosted on GitHub.
MIT License
32 stars 3 forks source link

Tune `relativeImageRegex` used to find and update relative Image URL's #35

Open rnag opened 7 months ago

rnag commented 7 months ago

Hi @sinedied ! Thanks so much for coming up with this library.

I would request to look into tuning regex relativeImageRegex used in function updateRelativeImageUrls to update relative image URLs in a markdown with their absolute paths, in order to support more image link formats.

For example, this increasingly popular gist on a "how-to" for image resizing in GitHub markdown: https://gist.github.com/uupaa/f77d2bcf4dc7a294d109

I personally deploy my blog articles using Jekyll and GitHub Pages, so as mentioned in the same article, we might see this syntax in the wild in .md files used w/ Jekyll:

![alt](image.png){: width="50%"}

I have tested it extensively on my local. I believe I was able to update the regex to include an optional capturing group for the height and width modifier, such as {: height=200px } for example.

This is my updated regex I have tested with:

!\[(.*)]\((?!.*?:\/\/)([^ ]*?) *?( (?:'.*'|".*"))? *?\)( *\{ *\:? *(?:width|height) *[:=] *["'0-9%A-Za-z]+ *;? *})?

Snippet of relevant parts for while loop replacement I'm using in code:

    while ((match = relativeImageRegex.exec(article.content))) {
        const [
            link,
            alt = '',
            imagePath,
            title = '',
            sizeModifier = '',
        ] = match;

        if (imagePath) {
            // const fullPath = getFullImagePath(basePath, imagePath);
            const newLink = `![${alt}](${getResourceUrl(repository, branch)}${imagePath.replace(/^\/+/g, '')}${title})`;

            content = content.replace(link, newLink);
            if (sizeModifier)
                content = content.replace(sizeModifier, '');
        }
    }

Regex Playground can be found here: https://regex101.com/r/r6HJT8/1

Thanks, Ritvik

sinedied commented 2 months ago

Sorry for the delay, I missed your post.

I'd welcome a PR that updates the RegExp, as long as you add some unit tests with it 🙂