URL:修订间差异
来自康健生活
| (未显示同一用户的5个中间版本) | |||
| 第13行: | 第13行: | ||
== 参数 == | == 参数 == | ||
=== 获取参数 === | === 获取参数 === | ||
假定 URL 为 <code>https://kangkk.com/404?a=2</code>。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const getQuery = name => { | |||
const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); | |||
const r = window.location.search.substr(1).match(reg); | |||
if (r != null) return decodeURIComponent(r[2]); | |||
return null; | |||
} | |||
console.log(getQuery('a'));</syntaxhighlight>|{{consoleout|<pre> | |||
2 | |||
</pre>}}}} | |||
另一种处理方式。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const getQuery = name => { | |||
const params = window.location.search.substring(1).split("&"); | |||
for (let i = 0; i < params.length; i++) { | |||
const pair = params[i].split("="); | |||
if(pair[0] == name) return pair[1]; | |||
} | |||
return void 0; | |||
} | |||
console.log(getQuery('a'));</syntaxhighlight>|{{consoleout|<pre> | |||
2 | |||
</pre>}}}} | |||
=== URLSearchParams === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
let URL = "http://kangkk.com?a=2" | |||
const getQuery = url => { | |||
const urlSearchParams = new URLSearchParams(url.split('?')[1]); | |||
return Object.fromEntries(urlSearchParams.entries()); | |||
} | |||
console.log(getQuery(URL));</syntaxhighlight>|{{consoleout|<pre>{ a: '2' } | |||
</pre>}}}} | |||
== 参考 == | == 参考 == | ||
| 第19行: | 第56行: | ||
=== 附件 === | === 附件 === | ||
* [[文件:Rfc1738.txt|无|Rfc1738.txt]] | * [[文件:Rfc1738.txt|无|Rfc1738.txt]] | ||
* [[媒体:Rfc1738.txt|无]] | * [[媒体:Rfc1738.txt|无]] | ||