+ 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?
1 ответ
+ 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");