简体   繁体   中英

How can i get value from URL in java script

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

How do i get value " XYZ " from the url using javascript

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. Check the API docs for Location to see all the available values you have regarding the current URL.

For this specific example you have given. window.location.pathname will be /admin/parking/airportParkingPriorityUpdate/xyz .

You can split this easily with 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

Just to note that IE <=10 never includes the leading / in 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. Try below code.

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

getURLParameter("id") --> Returns 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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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