0

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!

1
  • You could just remove the #!/ like so window.location.hash.replace('#!/','') Commented Mar 16, 2017 at 12:09

4 Answers 4

2
window.location.hash.split('!/')[1]; // Outputs "https://example.com/"
Sign up to request clarification or add additional context in comments.

Comments

2

Meet REGEX.

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

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

6 Comments

Doesn't work on example.com/#!/THISPART because of the extra \/
@JeremyThille works fine for me when I've tried it, it returned THISPART
No, it returns !/THISPART. There is no match for #!/ in the test string.
@JeremyThille with your example of example.com/#!/THISPART window.location.hash will return #!/THISPART so there is #!/ to match?
WTF? What did I smoke? My brain wasn't working well these past 10 minutes. Apologies, you're absolutely right.
|
1

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.

1 Comment

I tried that and it worked a few days ago, I forgot to post an answer about it on this question but you did it really well. Thanks!
0
var webSplit = window.location.split('/#!/')[1];

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

2 Comments

Actually, the output would be undefined. window.location.hash returns everything after the hash, so remove the first forward slash in the split
Ahh! my mistake.

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.