1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.