home ~ projects ~ socials

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:

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


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

console.log(updated)
Output:
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

-- end of line --