javascript: combining regular expression patterns

2022-03-07

 | 

~2 min read

 | 

310 words

I was working on updating my blog and I wanted to have excerpts. Unfortunately, the excerpts were coming in with a lot of additional context that I didn’t really want. For example, if there was an image in the excerpt or different header styles.

So, I decided that I’d simply remove those tokens when I was parsing the excerpt.

To do this, I needed a few different RegEx patterns. Because RegEx can be difficult to parse at the best of times, I wanted to name my patterns in a way that I might have a chance at remembering what they did in the future.

Turns out this is pretty easy in Javascript:

const imagePattern = new RegExp(/(!\[\]\(.*\))/g)
const headerPattern = new RegExp(/(#+)/g)
const quotesPattern = new RegExp(/((^|\n)>\s)/g)

const pattern = new RegExp(
  imagePattern.source + "|" + headerPattern.source + "|" + quotesPattern.source,
  "g",
)

const str =
  "#Section Header\nHere's a string with all sorts of things I don't want in it. Like this image ![](/path/to/image).\n> And quotes too!\nOh my!"

const cleaned = str.replace(pattern, "")

console.log({ str, cleaned, pattern })
{
  str: '#Section Header\n' +
    "Here's a string with all sorts of things I don't want in it. Like this image ![](/path/to/image).\n" +
    '> And quotes too!\n' +
    'Oh my!',
  cleaned: 'Section Header\n' +
    "Here's a string with all sorts of things I don't want in it. Like this image .And quotes too!\n" +
    'Oh my!',
  pattern: /(!\[.*\]\(.*\))|(#+)|((^|\n)>\s)/g
}

And here’s a repl for playing around.

We could generalize this pattern with a utility function:

const getComposedRegex = (flags: string, ...regexes: RegExp[]) =>
  new RegExp(regexes.map((regex) => regex.source).join("|"), flags)

getComposedRegex(imagePattern, headerPattern, quotesPattern)

Thanks to this Stack Overflow conversation for the inspiration!

The only thing I don’t love about my variant of getComposedRegex is that flags are now required in order for the function to operate as expected.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!