如何从JavaScript中的URL中提取查询字符串参数

时间:2018-11-12 17:42:18

标签: javascript

我有一个网址

  

https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama

我想获得search_terms(发电机+维修)和geo_location_terms(Adamsville%2C + Alabama)

我该怎么做?

3 个答案:

答案 0 :(得分:0)

您可以使用以下Javascript代码将GET参数存储到对象中:

<script>
    var URL = "https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama";

    var result = {};
    URL.substring(URL.indexOf("?") + 1).split('&').forEach(function(x){
        var arr = x.split('=');
        arr[1] && (result[arr[0]] = arr[1]);
    });

    console.log(result.search_terms);
    //OUTPUT: "Generator+Repair"
    console.log(result.geo_location_terms);
    //OUTPUT: "Adamsville%2C+Alabama"

</script>

答案 1 :(得分:0)

您可以使用以下正则表达式获取2个值:

/search_terms=(.*)&geo_location_terms=(.*)/

这是一个非常基本的正则表达式,首先匹配“ search_terms=”,然后创建一个Group,该{@ 1}}匹配任意数量的any char直至'&'符号,然后匹配'geo_location_terms=',最后创建一个与任意数量的any char匹配的组。

您所需的输出将在Group 1Group 2中。

使用方法:

var url = 'https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama';
var regex = /search_terms=(.*)&geo_location_terms=(.*)/;
var match = url.match(regex);

var search_terms = match[1];
var geo_location_terms = match[2];

答案 2 :(得分:0)

在JavaScript中最简单,最惯用的方法是使用URL类:

const url = new URL('https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama')

console.log(url.searchParams.get('search_terms'));
console.log(url.searchParams.get('geo_location_terms'));

MDN参考here