简体   繁体   中英

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 thoughts?

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

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.

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