+ 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?
2 Respuestas
+ 3
You will have to use the RegExp constructor along with concatenation or template literals.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Constructor
https://code.sololearn.com/WCuv7oJLB0aT/#js
0