Simon
Simon

Reputation: 23149

is there any function like php explode in jquery?

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

Upvotes: 9

Views: 19792

Answers (5)

rob waminal
rob waminal

Reputation: 18419

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

Upvotes: 2

Fermin
Fermin

Reputation: 36111

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.

Upvotes: 1

meo
meo

Reputation: 31249

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

Upvotes: 0

jAndy
jAndy

Reputation: 236122

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

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

Upvotes: 1

bobince
bobince

Reputation: 536615

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.

Upvotes: 18

Related Questions