简体   繁体   中英

How to get JavaScript regular expression without the querying part?

For example, if I have urls like url = ['aaa.com/subject/12345', 'aaa.com/book/45678'] . I want to get "subject" and "ebook" and the number out of it.

If I use url[i].match(/\\/(\\w)*\\//) , it will return ["/subject/", "t"] and ["/book/", "k"] for i equals 0 and 1 .

Of course, I can use slice(1, -1) to get "subject" and "book" .

But is it possible to use regular expression only to get "subject" instead of "/subject/" ?

You can use:

var url = ['aaa.com/subject/12345', 'aaa.com/book/45678'];
var m = url[0].match(/\/(\w+)\/(\d+)$/);
//=> ["/subject/12345", "subject", "12345"]

Now you can use m[1] to get subject and use m[2] to get number after it.

You need to place the quantifier within the capturing parentheses:

url[i].match(/\/(\w*)\//)

which will give you ["/subject/", "subject"] and ["/book/", "book"] .

The first element of the list of matches always contains the entire match.

If you repeat the capturing group itself, only the last repetition's match will be stored in the group's backreference.

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