我有一个网址
我想获得search_terms
(发电机+维修)和geo_location_terms
(Adamsville%2C + Alabama)
我该怎么做?
答案 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 1
和Group 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。