+ 1

How to 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; ... note: in the above code, the variable adjectives contains the adjectives: blue, pretty, blue... That's an example. So, how do we use a variable inside a regex?

1st Sep 2020, 6:47 PM
Ginfio
Ginfio - avatar
2 odpowiedzi
+ 3
1st Sep 2020, 10:10 PM
ODLNT
ODLNT - avatar
0
1st Sep 2020, 6:48 PM
Ginfio
Ginfio - avatar