简体   繁体   English

需要使用输入参数获取正确的JavaScript语法

[英]Need to get right javascript syntax with input parameters

I have js line like that agent.match(/(iphone|ipod|ipad)/) I need to make match parameters dynamic 我有像该agent.match(/(iphone|ipod|ipad)/)这样的js行,我需要使匹配参数动态化

So i tried to go like that agent.match('/(' + param + ')/') but it is not working. 所以我试着去像那个agent.match('/(' + param + ')/')但是它不起作用。 Whatever I put in param it is matching. 无论我在param什么,它都是匹配的。

What I did wrong? 我做错了什么? And what / means? 什么/手段?

When you are dynamically generate RegEx strings, its always better to use RegExp constructor. 动态生成RegEx字符串时,最好使用RegExp构造函数。 / is actually to tell JavaScript that you are going to use a Regular Expression literal. /实际上是告诉JavaScript您将使用正则表达式文字。 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. 我们可以将()与该字符串连接起来,以动态生成所需的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM