I have js line like that agent.match(/(iphone|ipod|ipad)/)
I need to make match parameters dynamic
So i tried to go like that agent.match('/(' + param + ')/')
but it is not working. Whatever I put in param
it is matching.
What I did wrong? And what /
means?
When you are dynamically generate RegEx strings, its always better to use RegExp
constructor. /
is actually to tell JavaScript that you are going to use a Regular Expression literal. But when you put that inside quotes, it becomes a part of the string.
The simplest way to do this is to put them in a list like this
var data = ["iphone", "ipod", "ipad"];
And join them with |
like this
agent.match(new RegExp("(" + data.join("|") + ")"))
This works because,
data.join("|")
will produce
iphone|ipod|ipad
We can concatenate (
and )
with that string to dynamically generate the pattern you wanted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.