views:

41

answers:

3

I'm trying to break a location.hash into an array using a RegEx. I can't for the life of me get the RegEx right.

the location.hash can be either "#/A/B/C/D" or "#/A/B/C/D/"

and must break down into "A", "B", "C", "D".

+2  A: 

Doesn't get much easier than:

var a = location.hash.split('/');

You still get # as first result, but you can easily remove or ignore it.

Kobi
Well, that's an easier solution.
Allan
@Allan - that *is* a Regex `:)`, split is using a regex anyway, but it is dead simple in this case.
Kobi
If you must, you can use `var a = location.hash.match(/[^#\/]+/g);`, but you don't really need it here.
Kobi
Using 'split' does seem to be the most obvious, and easier to uderstand for anybody who has to maintain the code in future. Using var a = location.hash.split('/').shift(); will get rid of the '#', leaving and array with "A", "B", "C", "D" in it.
belugabob
+1  A: 

I'd trim the leading/trailing guff then split on /:

location.hash.replace(/^#\/|\/$/g, '').split('/');
harto
A: 

match this regex-

(?<=/)[^/]*
Gopi