简体   繁体   English

我如何从 java 脚本中的 URL 获得价值

[英]How can i get value from URL in java script

http://localhost:3000/admin/parking/airportParkingPriorityUpdate/ xyz http://localhost:3000/admin/parking/airportParkingPriorityUpdate/ xyz

How do i get value " XYZ " from the url using javascript我如何使用 javascript 从 url 获得价值“ XYZ

const list = location.href.split('/');
list[list.length-1]

 let url = "http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz"; let parts = url.split("/"); let final = parts[parts.length - 1]; console.log(final);

The window.location object gives you everything you need to accomplish this. window.location object 为您提供完成此任务所需的一切。 Check the API docs for Location to see all the available values you have regarding the current URL.查看API 文档的 Location以查看有关当前 URL 的所有可用值。

For this specific example you have given.对于您给出的这个特定示例。 window.location.pathname will be /admin/parking/airportParkingPriorityUpdate/xyz . window.location.pathname将是/admin/parking/airportParkingPriorityUpdate/xyz

You can split this easily with window.location.pathname.split('/') .您可以使用window.location.pathname.split('/')轻松拆分它。 It's then a case of taking the last array value from the result.然后是从结果中获取最后一个数组值的情况。

const path = window.location.pathname;
const parts = path.split('/');
const result = parts[parts.length - 1];

<= IE 10 <= IE 10

Just to note that IE <=10 never includes the leading / in window.location.pathname .请注意,IE <=10 从不包括window.location.pathname中的前导/

You could use a regular expression:您可以使用正则表达式:

 // create a url - object let url = new URL('http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz'); // use just the pathname of the url (if there would exist url - params in the url they would be filtered out) let result = url.pathname.match(/((?.\/);)+$/)[0]. // use the result however you want console.log(result)

You can also get URL parameters using javaScript.您还可以使用 javaScript 获取 URL 参数。 Try below code.试试下面的代码。

http://localhost/mypage?id=10&name=Simy http://localhost/mypage?id=10&name=Simy

getURLParameter("id") --> Returns 10 getURLParameter("id") --> 返回 10

 function getURLParameter(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); if(pair[0] == variable){return pair[1];} } return(false); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM