JavaScript/url:修订间差异
来自康健生活
创建页面,内容为“== 引言 == == location == {| class="wikitable" |- | hash || 从 <code>#</code> 开始的 URL |- | host || 主机名 + 端口号 |- | hostname || 当前 URL 的主…” |
|||
| (未显示同一用户的2个中间版本) | |||
| 第19行: | 第19行: | ||
| serach || 从 <code>?</code> 开始的 URL | | serach || 从 <code>?</code> 开始的 URL | ||
|} | |} | ||
== 正则 == | |||
<syntaxhighlight lang="javascript"> | |||
function getQueryString(name) { | |||
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); | |||
let r = window.location.search.substr(1).match(reg); | |||
if (r != null) { | |||
return unescape(r[2]); | |||
}; | |||
return null; | |||
}</syntaxhighlight> | |||
== split == | |||
<syntaxhighlight lang="javascript"> | |||
function GetRequest() { | |||
const url = location.search; //获取url中"?"符后的字串 | |||
let theRequest = new Object(); | |||
if (url.indexOf("?") != -1) { | |||
let str = url.substr(1); | |||
strs = str.split("&"); | |||
for(let i = 0; i < strs.length; i ++) { | |||
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); | |||
} | |||
} | |||
return theRequest; | |||
}</syntaxhighlight> | |||
<syntaxhighlight lang="javascript"> | |||
function getUrlParams(name) { // 不传name返回所有值,否则返回对应值 | |||
var url = window.location.search; | |||
if (url.indexOf('?') == 1) { return false; } | |||
url = url.substr(1); | |||
url = url.split('&'); | |||
var name = name || ''; | |||
var nameres; | |||
// 获取全部参数及其值 | |||
for(var i=0;i<url.length;i++) { | |||
var info = url[i].split('='); | |||
var obj = {}; | |||
obj[info[0]] = decodeURI(info[1]); | |||
url[i] = obj; | |||
} | |||
// 如果传入一个参数名称,就匹配其值 | |||
if (name) { | |||
for(var i=0;i<url.length;i++) { | |||
for (const key in url[i]) { | |||
if (key == name) { | |||
nameres = url[i][key]; | |||
} | |||
} | |||
} | |||
} else { | |||
nameres = url; | |||
} | |||
// 返回结果 | |||
return nameres; | |||
}</syntaxhighlight> | |||
这些示例代码都有问题,有待改正 | |||