Shibbir
Shibbir

Reputation: 2041

How to get parts of a URL string using Javascript?

I have this URL:

var url = "mysite.com/categorias/#tab-cultura/folclore/";

now I want to get 2 string from that URL:

#tab-cultura and folclore

how can I get it using Javascript?

url.split('#')[0];

It seems this split is not the right solution:(

Upvotes: 0

Views: 1051

Answers (5)

Damon
Damon

Reputation: 10808

Using Array.split() will probably get you what you need — for now, but URLs are inherently quite complicated and you want to make sure the code will function the same way on different servers with variable query parameters etc. It may be more reliable to use built in browser functionality:

const hash = new URL("http://example.com/categorias/#tab-cultura/folclore/").hash

// => "#tab-cultura/folclore/"

hash.split('/') 

// => ['#tab-cultura', 'folclore', ''] 

hash.split('/').filter(i=>i)

// => ['#tab-cultura', 'folclore']

Note: new URL() is not available in IE, but can be polyfilled.

Upvotes: 0

zb22
zb22

Reputation: 3231

You can use split('/') like so:

var url = "mysite.com/categorias/#tab-cultura/folclore/";

let [, ,tabCultura, folclore] = url.split('/');

console.log(tabCultura);
console.log(folclore);

Upvotes: 0

Mohammad
Mohammad

Reputation: 21499

You need to split your URL by / delimiter instead

var url = "mysite.com/categorias/#tab-cultura/folclore/";
var parts = url.split('/');
console.log(parts[2]);
console.log(parts[3]);

Also you can use regex if you don't know position of # in URL

var url = "mysite.com/categorias/category1/category2/#tab-cultura/folclore/";
var parts = url.match(/(#[^\/]+)\/([^\/]+)/);
console.log(parts[1]);
console.log(parts[2]);

Upvotes: 2

PassionateCoder
PassionateCoder

Reputation: 41

With JavaScript’s String.prototype.split function:

var url = "mysite.com/categorias/#tab-cultura/folclore/";
var fields = input.split('/');

var first = fields[0];
var second = fields[1];
var third = fields[2];
var fourth = fields[3];

Upvotes: 0

Nitish Narang
Nitish Narang

Reputation: 4184

"Split" can be correct way to approach this. Pls see below

var url = "mysite.com/categorias/#tab-cultura/folclore/";

let [val1, val2] = url.split('#')[1].split('/')

console.log(val1, val2)

Upvotes: 4

Related Questions