简体   繁体   中英

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

I want to get search_terms (Generator+Repair) and 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:

 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 .

You can use the following Javascript code to store the GET parameters into an object:

<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:

/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 .

Your desired output will be in Group 1 and Group 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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