javascript - Variables in regexp -
this question has answer here:
- passing variable regexp in javascript [duplicate] 4 answers
- how use variable in regular expression? 16 answers
i have regexp:
if (/(name|surname|city|dog)/.test(names)) { alert('true'); } i use variables instead , pass regexp, like:
$name = 'name'; $surname = 'surname'; $city = 'city'; $dog = 'dog'; if (/($name|$surname|$city|$dog)/.test(names)) { alert('true'); } this code doesn't work. corrent 1 purpose?
i know how can done using regexp.
var args = ['name', 'surname', 'city', 'dog']; var regexp = new regexp(args.join("|")); if (regexp.test(names)) { alert('true'); } more generally, need concatenate arguments string inside new regexp object. depending on in variables, may need escape them first - there ample places on stackoverflow find regular expression escaping advice.
Comments
Post a Comment