简体   繁体   中英

Capture groups with javascript regex

I have a url string from which I want to capture all the words between the / delimiter:

So given this url:

"/way/items/add_items/sell_items":

I want to capture:

way
items
sell_items
add_items

If I do it like this:

'/way/items/sell_items/add_items'.match(/(\w+)/g)
=> [ 'way', 'items', 'sell_items', 'add_items' ]

It will give me an array back but with no capturing groups, why I do this instead:

new RegExp(/(\w+)/g).exec("/way/items/sell_items/add_items")
=> [ 'way', 'way', index: 1, input: '/way/items/sell_items/add_items' ]

But this only captures way .. I want it to capture all four words.

How do I do that?

Thanks

You should write

var parts = url.split("/");

The global flag is used to the replace method.
Also, it makes the exec method start from the last result (using the RegExp 's lastIndex property)

If you need by some reasons an exactly Regex, so use this, else use split() function.

Code:

var re = new RegExp(/\w+?(?=\/|$)/gi);  // added |$
alert(re);
var text = '/way/items/add_items/sell_items';
var aRes = text.match(re);

Result: [way, items, add_items, sell_items];

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