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 aRegExp
object. You don't need to call the constructor. – SLaks Commented Mar 31, 2011 at 3:41
2 Answers
Reset to default 9You 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
版权声明:本文标题:Capture groups with javascript regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741252037a2365973.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论