Get GET variables from url using JavaScript jQuery

旧巷老猫 提交于 2019-12-11 06:09:22

问题


I want to read out a GET variable from an url using jquery

The domain is displayed like this

http://example.com/p/kT2Rnu35

And the original is :

http://example.com/php/page.php?id=kT2Rnu35

I want to get that id using jQuery from the page with the domain http://example.com/p/kT2Rnu35

I've tried window.location and other functions i found on stack overflow but nothing worked. Is it because i'm changing the url using htaccess ?


回答1:


window.location.href will give you the url with parameters

From there just use .split to break it apart




回答2:


const getParameterByName = (name, url) => {
  const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
  const results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
};

let url = 'https://website.com/abc?id=123';

console.log(getParameterByName('id', url));

// For url like this `http://example.com/p/kT2Rnu35` simply get the last token after `/`

url = 'http://example.com/p/kT2Rnu35';
let id = url.substring(url.lastIndexOf('/') + 1);
console.log(id);


来源:https://stackoverflow.com/questions/50338016/get-get-variables-from-url-using-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!