0

I'm trying to echo current url after ? with # symbol. But it isn't possible with php. So I have to do that with javascript. But I have no knowledge about javascript. This is the url:

https://example.com/r/?https://mega.nz/#!link!pass

I want to get after ? like:

https://mega.nz/#!link!pass

And echo to screen with php.

I tried everything I've found but I didn't make it.

<script type="text/javascript">
var pageName = (function () {
var a = window.location.href,
b = a.lastIndexOf("#");
return a.substr(b + 1);
}());
$(document).ready(function(){
$("#element-id").html(pageName());
});
</script>
<?php
echo '<div id="element-id"></div>';
?>

I expect the output

https://mega.nz/#!link!pass But the actual output is empty.

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
Baran
  • 1
  • 1
  • That code for getting the hash fragment works for me. There's a much simpler way to do it, but that works for me. – T.J. Crowder Apr 23 '19 at 12:47
  • Of topic question: is this url kinda Get url, should it have in that case some parameter name after ? -mark?Like "link=https://mega.nz/#!link!pass" ? – maximelian1986 Apr 23 '19 at 12:51
  • 1
    @T.J.Crowder, but he wrapped it inside $(document).ready() – maximelian1986 Apr 23 '19 at 12:53
  • https://site.pm/url={$url} I'm trying to set https://mega.nz/#link!pass section as $url. Everyone gave me the correct way. But I couldn't set as a variable. – Baran Apr 23 '19 at 12:55
  • @maximelian1986 - Doh! Thanks! @ Baran - That code should work. Please update the question with a [mcve] (it has to be **in** the question, not linked, see [*Something in my web site or project doesn't work. Can I just paste a link to it?*](https://meta.stackoverflow.com/questions/254428/)). When you've done that, please ping me in the comments (type @ and then pick my name from the list) and I'll reopen the question. – T.J. Crowder Apr 23 '19 at 13:11

2 Answers2

0

To get the fragment portion of a URL, use its hash property:

var pageName = location.hash;

That will start with a # if there's any hash on the window (but will be "" if there isn't). If you don't want the #, then

var pageName = location.hash;
if (pageName.startswith("#")) {
    pageName = pageName.substring(1);
}
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • When i posted this answer, I assumed the OP's code didn't work. But it does, it's just a different way to solve the problem. So...hmmm.... – T.J. Crowder Apr 23 '19 at 12:48
0

Use window.location.href to get the full URL - it works perfectly.

To get the hash (e.g. #link), use window.location.hash:

var pageName = window.location.hash;
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67