Get GET variables from url using JavaScript jQuery

2019-08-15 07:44发布

问题:

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