简体   繁体   English

javascript正则表达式:字符串中的匹配值

[英]javascript regex: match value within string

I have this expression to check wether if a key exists in a url : 我有这个表达式来检查是否在URL中存在键:

new RegExp('/'+x+'/ig')

(removed the irrelevant code) (删除了不相关的代码)

Thing is, it isn't working. 问题是,它不起作用。 I suppose I have to use delimiters (start and end) to work, since the url has many other things, but not sure how to do it. 我想我必须使用定界符(开始和结束)来工作,因为URL还有很多其他事情,但不确定如何执行。

Any thoughts? 有什么想法吗?

When you use new Regex() , you have to pass the flags as a second parameter 使用new Regex() ,必须将标志作为第二个参数传递

new RegExp(x, 'ig')

Note that you don't need the literal delimiters when you create a RegExp this way 请注意,当你创建一个你不需要文字分隔符RegExp这样

It kinda looks like you're mixing regexp literals and strings. 看起来您正在混合使用正则表达式文字和字符串。

One way to write a regexp is like this: 编写正则表达式的一种方法是这样的:

var myExp = new RegExp('[a-z]*')

It matches any number of letters from az, any number of times. 它可以匹配任意数量的z字母。 Another way to do the same thing would be like this: 做同一件事的另一种方法是这样的:

var myExp = /[a-z]*/

or even 甚至

var myExp = /[a-z*]/ig

where ig means "ignore case" and "global". 其中ig表示“忽略大小写”和“全局”。

So, stick to one way of writing it. 因此,请坚持一种编写方式。 Don't mix strings and literals. 不要混合使用字符串和文字。

Edit: 编辑:

If you want to use the first syntax, but also ignore case and make the match global, pass the string 'ig' as a second argument to the RegExp-constructor ( new RegExp('[az]*', 'ig') ) 如果要使用第一种语法,但也忽略大小写并使全局匹配,请将字符串'ig'作为第二个参数传递给RegExp-constructor( new RegExp('[az]*', 'ig')

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

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