home ~ socials ~ projects ~ rss

Use A Variable In A JavaScript Regular Expression

October 2022

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
Share link:
https://www.alanwsmith.com/en/2g/td/co/wb/?use-a-variable-in-a-javascript-regular-expression