tags:

views:

53

answers:

5

i have a string path1/path2

i need to get the values of path1 and path2.

how can i do it? (maybe regex? but i don't know their construction, maybe you'll hekp me:/


and what about getting the same from such string http://www.somesite.com/#path1/path2?

Thanks

+6  A: 

The plain JavaScript String object has a split method.

'path1/path2'.split('/')

'http://www.somesite.com/#path1/path2'.split('#').pop().split('/')

-> ['path1', 'path2']

However, for the second case, it's generally not a good idea to do your own URL parsing via string or regex hacking. URLs are more complicated than you think. If you have a location object or an <a> element, you can reliably pick the parts of the URL out of it using the protocol, host, port, pathname, search and hash properties.

bobince
and what about the second string?
Syom
+1 for using pop() !
meo
+1  A: 
var url = 'http://www.somesite.com/#path1/path2';
var arr = /#(.*)/g.exec(url);

alert(arr[1].split('/'));
jAndy
A: 

I don't think you need to use jQuery for this, Javascripts plain old Split() method should help you out.

Also, for your second string if you're dealing with URL's you can have a look at the Location object as this gives you access to the port, host etc.

Fermin
A: 

You can use the javascript 'path1/path2'.split('/') for example. Gives you back an array where 0 is path1 and 1 is path2.

There is no need to use jquery

meo
+1  A: 
var path1 = "path1/path2".split('/')[0];
var path2 = "path1/path2".split('/')[1];

for the 2nd one, if you are getting it from your url you can do this.

var hash = window.location.hash;
var path1 = hash.split('#')[1].split('/')[0];
var path2 = hash.split('#')[1].split('/')[1];
rob waminal