9

I have a string path1/path2

I need to get the values of path1 and path2.

how can i do it?


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

Thanks

0

5 Answers 5

18

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.

Sign up to request clarification or add additional context in comments.

Comments

2
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];

Comments

1
var url = 'http://www.somesite.com/#path1/path2';
var arr = /#(.*)/g.exec(url);

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.