开发者

javascript regex: match value within string

I have this expression to check wether if a key exists in a 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.

Any t开发者_如何学Gohoughts?


When you use new Regex(), you have to pass the flags as a second parameter

new RegExp(x, 'ig')

Note that you don't need the literal delimiters when you create a RegExp this way


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 a-z, any number of times. 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".

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('[a-z]*', 'ig'))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜