Get GET variables from url using JavaScript jQuery

2019-08-15 07:26发布

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 ?

2条回答
smile是对你的礼貌
2楼-- · 2019-08-15 08:12

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);

查看更多
该账号已被封号
3楼-- · 2019-08-15 08:22

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

From there just use .split to break it apart

查看更多
登录 后发表回答