0

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:(

2
  • url.split('#')[1].split('/')[0] for the first and url.split('#')[1].split('/')[1] for second Commented Nov 17, 2018 at 9:44
  • yes, you want two strings... but based on what?? Commented Nov 17, 2018 at 9:45

5 Answers 5

4

"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)

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

5 Comments

Yes it's array destructuring.
Short form of let val1 = url.split('#')[1].split('/')[0], val2 = let val2= url.split('#')[1].split('/')[1]
I found an issue if the url is like that: abc-dev.totalcommit.com/categorias/#tab-educacao/abs
oh, not it's fine.
Yes @creativeartbd it will work fine for your mentioned case as well. All the best Happy Coding!! :)
2

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

1 Comment

Oh, great. Working fine.
0

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

Comments

0

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

Comments

0

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.

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.