简体   繁体   English

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

[英]How to extract query string parameters from URL in JavaScript

I have a URL 我有一个网址

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

I want to get search_terms (Generator+Repair) and geo_location_terms (Adamsville%2C+Alabama) 我想获取search_terms (发电机+维修)和geo_location_terms (Adamsville%2C + Alabama)

How I can do this? 我该怎么做?

The easiest and most idiomatic way to do this in JavaScript is using the URL class: 在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 reference here . MDN参考在这里

You can use the following Javascript code to store the GET parameters into an object: 您可以使用以下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>

You can use the following regex to get the 2 values: 您可以使用以下正则表达式获取2个值:

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

This is a very basic regex, that starts by matching ' search_terms= ' then creates a Group that matches any number of any char up to the '&' sign, then matches ' geo_location_terms=' and finally creates a Group that matches any number of any char . 这是一个非常基本的正则表达式,首先匹配“ search_terms= ”,然后创建一个匹配任何数量的any charGroup ,直到'&'号,然后匹配“ geo_location_terms=' ,最后创建一个匹配任何数量的Group的正则表达式。 any char

Your desired output will be in Group 1 and Group 2 . 您所需的输出将在Group 1 Group 2Group 2

How to use: 如何使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM