Adi
Adi

Reputation: 51

Splitting Web Page URL but Not URL After the Hash in JavaScript

So I tried getting the text after my URL like this "example.com/#!/THISPART" with the code below:

var webSplit = window.location.hash.split('/')[1];

And It works but if I supply another URL after like this "example.com/#!/https://example.com/" it gives this as output "https" which I don't want. I want the whole URL. Can someone help me out? Thanks!

Upvotes: 0

Views: 194

Answers (4)

Seth
Seth

Reputation: 1255

The actual problem is that your approach for the split is incorrect.

With your example window.location.hash return #!/https://example.com/. What you#re doing is splitting that element by / and using the second element of the result.

The result of the split would be 4 elements ([ "#!", "https:", "", "example.com" ]) and the second element would be just he https:. What you need to do, do fix it is either find an another delimiter or find another way to extract the URL.

With your current example you could !/ for the split to get two elements back ([ "#", "https://example.com" ]) where the second one would be the whole URL, as long as it doesn't contain the string !/. Another appraoch would be to find the first occurrence of http from the left and take a substring from what position until the end of it.

Other answers show some different solution.

Upvotes: 1

Rana Ghosh
Rana Ghosh

Reputation: 4674

var webSplit = window.location.split('/#!/')[1];

Output will be :: https://example.com/ as ou want.

Upvotes: 0

Mitya
Mitya

Reputation: 34596

Meet REGEX.

var part = location.hash.replace(/#!\//, '');

That'll give you whatever's after #!/.

Upvotes: 2

Jeremy Thille
Jeremy Thille

Reputation: 26400

window.location.hash.split('!/')[1]; // Outputs "https://example.com/"

Upvotes: 2

Related Questions