+ 1

insert a variable in a regex _

var adjectives = "blue|pretty|big"; regex = /blue is an adjective/i; Let's say I need to use the adjectives above multiple times. So, instead of doing: var chance1 = /(blue|pretty|big) is an adjective/i; var chance2 = /(blue|pretty|big) is definitely an adjective/i; var chance3 = /(blue|pretty|big) is adjective/i; Instead I want to do something like var chance1 = /(+adjectives+) is an adjective/i; var chance 2 = /(+adjectives+) is definitely an adjective/i; ... That's an example. So, how do we use a variable inside a regex?

1st Sep 2020, 6:47 PM
Ginfio
Ginfio - avatar
1 Réponse
+ 2
That's when the RegExp constructor comes into play: RegExp (pattern, flags) E.g: var adj = "(some|adjetives)"; var re = new RegExp (adj, "i");
2nd Sep 2020, 6:33 AM
Kevin ★