从URL字符串获取常量变量

时间:2018-08-24 20:58:58

标签: javascript url getvalue

我正在尝试在网站的URL字符串中隔离常量。例如www.website.com/products/brand-product-description?variant=123456789。我需要一个仅返回'123456789'的js函数

2 个答案:

答案 0 :(得分:0)

您可以使用URL对象并使用其searchParams.get函数。在较旧的浏览器中,您可以使用以下网址polyfill:https://github.com/lifaon74/url-polyfill/blob/master/url-polyfill.js

function getParam(url, param){
  var link = new URL(url);
  return link.searchParams.get(param);
}
console.log(getParam("http://www.website.com/products/brand-product-description?variant=123456789", "variant"));

答案 1 :(得分:-1)

How can I get query string values in JavaScript?

看看文章。要点如下:

 function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}       
    
console.log(getParameterByName('variant', 'www.website.com/products/brand-product-description?variant=123456789'));