Regex Recipes

I’ve always been terrible at regex (shouldn't have goofed off so much in Formal Languages). Here are some common snippets that come in handy.

Get URLs from the src attribute of an HTML image tag

const srcRegex = /<img.*?src=['"](.*?)['"]/
const src = srcRegex.exec(string)[1]
// string = "<img src='http://link-to-image.com/image.png' />"
// src = "http://link-to-image.com/image.png"

Test whether a URL is internal or not

const internal = /^\/(?!\/)/.test(url)

Strip HTML tags out of a string

const stripHTML = string => string.replace(/<[^>]+>/g, '')