Home

Use A Variable In A JavaScript Regular Expression

** TL;DR

Create a new [TODO: Code shorthand span ] object to use a variable in a regex pattern match. For example:

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


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

console.log(updated)
results start

#+NOTES:

- The example only shows one replacement but every instance of [TODO: Code shorthand span ] in the [TODO: Code shorthand span ] string would be replace with [TODO: Code shorthand span ] due to the use of [TODO: Code shorthand span ] and the [TODO: Code shorthand span ] flat which sets things to work globally

- The example uses [TODO: Code shorthand span ] to make the match case insensitive

~ fin ~