Reputation: 71
I have a URL
I want to get search_terms
(Generator+Repair) and geo_location_terms
(Adamsville%2C+Alabama)
How I can do this?
Upvotes: 0
Views: 268
Reputation: 5303
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.
Upvotes: 1
Reputation: 10929
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];
Upvotes: 0
Reputation: 846
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>
Upvotes: 0