最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get id from URL parameters - Stack Overflow

programmeradmin2浏览0评论

My project is using React 16.9^ with Hooks and I'm trying to get the parameter from the URL.

http://localhost:3000/kontakt/confirm-account?token=d5b72ed2-ebb3-4da9-8619-1223234950a5

I need to detach the last part:

confirm-account?token=d5b72ed2-ebb3-4da9-8619-1223234950a5


Whats the best practice to do this? Any suggestions on how this could be done would be much appreciated.

My project is using React 16.9^ with Hooks and I'm trying to get the parameter from the URL.

http://localhost:3000/kontakt/confirm-account?token=d5b72ed2-ebb3-4da9-8619-1223234950a5

I need to detach the last part:

confirm-account?token=d5b72ed2-ebb3-4da9-8619-1223234950a5


Whats the best practice to do this? Any suggestions on how this could be done would be much appreciated.

Share Improve this question asked Oct 31, 2019 at 12:51 ArastoArasto 4916 silver badges27 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3
window.location.href.split('/').reverse()[0]

Another example: w3schools snippet

var allUrl =  window.location.href
var result = window.location.href.split('/').reverse()[0]

document.getElementById("fullUrlId").innerHTML = "full url: " + allUrl ;
document.getElementById("resultId").innerHTML = "url after split: " + result;
<div id= "fullUrlId"> url </div>
<div id= "resultId"> result </div>

You can get the window.location and extract this part

console.log(window.location)

Do you actually need the whole part after the last /? Because you can get the url parameters (after ?) easy with window.location.search Otherwise you need a string manipulation function

<script>
    var urlParams = new URLSearchParams(window.location.search);
    console.log(urlParams.toString()); // this will log the part you need: urlParams.toString()
</script>

if you are trying to do token based authentication system you can send token on every request header x-access-token and verify that on server side (middleware)

发布评论

评论列表(0)

  1. 暂无评论