Skip to content Skip to sidebar Skip to footer

How To Retrieve All Parts Of Path-like String Using Regular Expressions?

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

Solution 1:

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.


Post a Comment for "How To Retrieve All Parts Of Path-like String Using Regular Expressions?"