admin管理员组

文章数量:1277899

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

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

Share Improve this question edited Mar 31, 2011 at 3:42 ajsie asked Mar 31, 2011 at 3:36 ajsieajsie 79.8k110 gold badges284 silver badges386 bronze badges 1
  • 2 /.../ is already a RegExp object. You don't need to call the constructor. – SLaks Commented Mar 31, 2011 at 3:41
Add a ment  | 

2 Answers 2

Reset to default 9

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];

本文标签: Capture groups with javascript regexStack Overflow