1

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

1
  • 2
    /.../ is already a RegExp object. You don't need to call the constructor. Commented Mar 31, 2011 at 3:41

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, but be aware that the / at the start of the URL results in one empty array element.
4

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

3 Comments

This is PHP, while the question is concerned with JavaScript.
@jensgram: Thank you!. I changed my post. Javascript supports lookahead operations, but does not support lookbehind.
But match() doesn't give me captured groups ... just an array with the matches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.