Skip to content

Instantly share code, notes, and snippets.

@reeddunkle
Last active November 1, 2019 19:57
Show Gist options
  • Select an option

  • Save reeddunkle/a7f3b8a57d3b7903204b153023be9ee4 to your computer and use it in GitHub Desktop.

Select an option

Save reeddunkle/a7f3b8a57d3b7903204b153023be9ee4 to your computer and use it in GitHub Desktop.
Convert Markdown image link to HTML `<img>` with resize percent

Convert Markdown image link to HTML <img> with resize percent:

const resizeMdImg = (mdImgStr, size) => {
  if (!mdImgStr) return;

  const mdImgExpression = /^!\[(.*)\]\((.*)\)/;
  const { 1: alt, 2: src } = mdImgStr.match(mdImgExpression);
  const sizeStr = size ? ` height="${size}" width="${size}"` : "";

  const htmlStr = `<img alt="${alt}" src="${src}"` + sizeStr + ` />`;

  try {
    copy(htmlStr);
    console.log("Copied to clipboard.");
  } catch {}

  return htmlStr;
};

This is how I use it in the Chrome console:

// Paste in the function.

// Use `var` so I can mutate as I go:
var m = '![Sprint 2 #44 IE](https://user-images.githubusercontent.com/7785340/67798302-a04dd700-fa59-11e9-867c-221fb792071c.jpg)';

resizeMdImg(m, '50%');
// => Copied to clipboard.
// => "<img alt="Sprint 2 #44 IE" src="https://user-images.githubusercontent.com/7785340/67798302-a04dd700-fa59-11e9-867c-221fb792071c.jpg" height="50%" width="50%" />"

I keep mutating m and re-running the function as I go. It's crude, but does the trick for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment