Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Use A Variable In A JavaScript Regular Expression

** TL;DR

Create a new `RegExp` object to use a variable in a regex pattern match. For example:

Code

const target = 'quick'
const pattern = new RegExp(target, 'gi')


const source = 'the Quick dog'
const updated = source.replaceAll(pattern, 'slow')

console.log(updated)

Results

the slow dog

#+NOTES:

- The example only shows one replacement but every instance of `quick` in the `source` string would be replace with `slow` due to the use of `.replaceAll` and the `g` flat which sets things to work globally

- The example uses `i` to make the match case insensitive