0

For example I have a path of the following format:

f1/f2/f3/aaa

I would like to have matching groups to return something like this:

["f1", "f2", "f3", "aaa"]
Martin Ender
  • 43,427
  • 11
  • 90
  • 130
Mik Kardash
  • 630
  • 8
  • 17

1 Answers1

7

Don't use regular expressions for this:

var str = "f1/f2/f3/aaa",
    arr = str.split('/');
console.log(arr);

JS Fiddle demo.

This gets you a real array at the end, whereas with regular expressions, at best, you'd end up with an array-like string. Which seems somewhat pointless.

If you must use a regular-expression approach:

var str = "f1/f2/f3/aaa",
    arr = str.match(/(\w+)/g);
console.log(arr)​​​

JS Fiddle demo.

And just look how much less comprehensible that is. Also how fragile it is (since, with that approach, it requires the separator to be a non-alphanumeric (or _) character). There really is, in this instance, no good reason to use regular expressions.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • `/([^\/]+)/g` might make a better regex...just saying. :) But yeah, still not the right tool for the job. – cHao Nov 02 '12 at 19:12
  • @cHao: agreed but in the case of selecting all characters that *don't* match a `/` character? I'm *completely* sticking with the `split('/')` approach. Mainly due to my principle of refusing to over-complicate. =) – David Thomas Nov 02 '12 at 19:17