无法从网址获取一些参数 - 返回NaN / null

时间:2018-05-17 20:14:42

标签: javascript

我有这个简单的字符串:

var url_string = 'https://www.booking.com/searchresults.html?label=gen173nr-1DCAEoggJCAlhYSDNYBGjBAYgBAZgBMcIBCndpbmRvd3MgMTDIAQzYAQPoAQH4AQKSAgF5qAID;sid=2a2d61dc6122c8a17b369733693bc965;checkin_month=5&checkin_monthday=17&checkin_year=2018&checkout_month=6&checkout_monthday=1&checkout_year=2018&class_interval=1&dest_id=-90115&dest_type=city&dtdisc=0&from_sf=1&group_adults=3&group_children=0&inac=0&index_postcard=0&label_click=undef&no_rooms=1&offset=0&postcard=0&raw_dest_type=city&room1=A%2CA%2CA&sb_price_type=total&src=index&src_elem=sb&ss=Ni%C5%A1&ss_all=0&ssb=empty&sshis=0&ssne=Ni%C5%A1&ssne_untouched=Ni%C5%A1&'

我来自

var url_string = window.location.href;

var url = new URL(url_string);

这是我目前所在的地址。现在我想提取一些参数

var no_rooms = url.searchParams.get("no_rooms"); // 1

var group_children = url.searchParams.get("group_children"); // 0

var checkin_month = url.searchParams.get("checkin_month"); // NaN

如果checkin_month,一个字符串中存在的参数,它是一个数字,打印NaN怎么可能?我在这里缺少什么?

编辑: 我使用

替换了;字符串中的?
url_string.replace(/;/g, "?");

重复同样的过程,当我到达

var checkin_month = url.searchParams.get("checkin_month"); // I got null

EDIT2: 我应该用?代替&

1 个答案:

答案 0 :(得分:1)

由于url没有格式化,所以还有两种方法。

解决方案1:

;替换为&,使其成为查询参数。



var url_string = 'https://www.booking.com/searchresults.html?label=gen173nr-1DCAEoggJCAlhYSDNYBGjBAYgBAZgBMcIBCndpbmRvd3MgMTDIAQzYAQPoAQH4AQKSAgF5qAID;sid=2a2d61dc6122c8a17b369733693bc965;checkin_month=5&checkin_monthday=17&checkin_year=2018&checkout_month=6&checkout_monthday=1&checkout_year=2018&class_interval=1&dest_id=-90115&dest_type=city&dtdisc=0&from_sf=1&group_adults=3&group_children=0&inac=0&index_postcard=0&label_click=undef&no_rooms=1&offset=0&postcard=0&raw_dest_type=city&room1=A%2CA%2CA&sb_price_type=total&src=index&src_elem=sb&ss=Ni%C5%A1&ss_all=0&ssb=empty&sshis=0&ssne=Ni%C5%A1&ssne_untouched=Ni%C5%A1&'

var newUrlString = url_string.replace(/;/g, '&');
var url = new URL(newUrlString);
var checkin_month = url.searchParams.get("checkin_month");
console.log("checkin_month is " + checkin_month);




解决方案2: 从现有URL对象中解析字符串



var url_string = 'https://www.booking.com/searchresults.html?label=gen173nr-1DCAEoggJCAlhYSDNYBGjBAYgBAZgBMcIBCndpbmRvd3MgMTDIAQzYAQPoAQH4AQKSAgF5qAID;sid=2a2d61dc6122c8a17b369733693bc965;checkin_month=5&checkin_monthday=17&checkin_year=2018&checkout_month=6&checkout_monthday=1&checkout_year=2018&class_interval=1&dest_id=-90115&dest_type=city&dtdisc=0&from_sf=1&group_adults=3&group_children=0&inac=0&index_postcard=0&label_click=undef&no_rooms=1&offset=0&postcard=0&raw_dest_type=city&room1=A%2CA%2CA&sb_price_type=total&src=index&src_elem=sb&ss=Ni%C5%A1&ss_all=0&ssb=empty&sshis=0&ssne=Ni%C5%A1&ssne_untouched=Ni%C5%A1&'
var url = new URL(url_string);
var checkin_month = url.searchParams.get('label').split(';').find(e => e.includes('checkin_month')).split('=')[1] 
console.log("checkin_month is " + checkin_month)