js 獲取url中的參數 修改url 參數 移除url參數測試
var jsUrlHelper = { getUrlParam : function(url, ref) { var str = ""; // 若是不包括此參數 if (url.indexOf(ref) == -1) return ""; str = url.substr(url.indexOf('?') + 1); arr = str.split('&'); for (i in arr) { var paired = arr[i].split('='); if (paired[0] == ref) { return paired[1]; } } return ""; }, putUrlParam : function(url, ref, value) { // 若是沒有參數 if (url.indexOf('?') == -1) return url + "?" + ref + "=" + value; // 若是不包括此參數 if (url.indexOf(ref) == -1) return url + "&" + ref + "=" + value; var arr_url = url.split('?'); var base = arr_url[0]; var arr_param = arr_url[1].split('&'); for (i = 0; i < arr_param.length; i++) { var paired = arr_param[i].split('='); if (paired[0] == ref) { paired[1] = value; arr_param[i] = paired.join('='); break; } } return base + "?" + arr_param.join('&'); }, delUrlParam : function(url, ref) { // 若是不包括此參數 if (url.indexOf(ref) == -1) return url; var arr_url = url.split('?'); var base = arr_url[0]; var arr_param = arr_url[1].split('&'); var index = -1; for (i = 0; i < arr_param.length; i++) { var paired = arr_param[i].split('='); if (paired[0] == ref) { index = i; break; } } if (index == -1) { return url; } else { arr_param.splice(index, 1); return base + "?" + arr_param.join('&'); } } };
測試url
var url1 = "http://localhost?page=tpage&size=tsize&key=tkey"; console.log('----get-------') console.log(jsUrlHelper.getUrlParam(url1,'page')) console.log(jsUrlHelper.getUrlParam(url1,'size')) console.log(jsUrlHelper.getUrlParam(url1,'key')) console.log(jsUrlHelper.getUrlParam(url1,'other')) console.log('----del-------') console.log(jsUrlHelper.delUrlParam(url1,'page')) console.log(jsUrlHelper.delUrlParam(url1,'size')) console.log(jsUrlHelper.delUrlParam(url1,'key')) console.log(jsUrlHelper.delUrlParam(url1,'other')) console.log('----put-------') console.log(jsUrlHelper.putUrlParam(url1,'page','page')) console.log(jsUrlHelper.putUrlParam(url1,'size','size')) console.log(jsUrlHelper.putUrlParam(url1,'key','key')) console.log(jsUrlHelper.putUrlParam(url1,'other','other'))
輸出spa
----get------- tpage tsize tkey ----del------- http://localhost?size=tsize&key=tkey http://localhost?page=tpage&key=tkey http://localhost?page=tpage&size=tsize http://localhost?page=tpage&size=tsize&key=tkey ----put------- http://localhost?page=page&size=tsize&key=tkey http://localhost?page=tpage&size=size&key=tkey http://localhost?page=tpage&size=tsize&key=key http://localhost?page=tpage&size=tsize&key=tkey&other=other