Detailed explanation of how to obtain each part of the url

Take this URL as an example to explain

https://www.expamle.com/index.html#/myConcern?from=reduce&endTime=2023-12-02

The window.location object has the following properties:

window.location.href: Get or set the complete URL address.

https://www.expamle.com/index.html#/myConcern?from=reduce&endTime=2023-12-02

window.location.protocol: Gets or sets the protocol part of the URL (for example, http:, https:).

https:

window.location.host: Gets or sets the host part of the URL (including domain name and port number).

www.expamle.com

window.location.hostname: Gets or sets the hostname part of the URL (excluding the port number).

www.expamle.com

window.location.port: Gets or sets the port number part of the URL.

‘’

window.location.pathname: Gets or sets the path part of the URL.

‘/index.html’

window.location.search: Gets or sets the query string part of the URL (the parameter part starting with ?).
You will not be able to get the hash

‘’

window.location.hash: Gets or sets the fragment identifier part of the URL (the anchor part starting with #).

#/myConcern?from=reduce&endTime=2023-12-02

In addition to the above properties, window.location has some methods for page navigation and redirection:

window.location.assign(url): Load the specified URL in the current window.
window.location.replace(url): Replace the current page with the specified URL, no history record will be generated.
window.location.reload(): Reload the current page.

What if you want to get the content behind the url for a hash type url?
There is no ready-made method, we can only get the window.location.hash and intercept it

const data = window.location.hash.split('?')[1]

If you want to get it? The value of the parameter after

const params = new URLSearchParams(data)

Usage of URLSearchParams object

// 创建一个 URLSearchParams 对象,并传入查询字符串
const params = new URLSearchParams('?from=reduce&endTime=2023-12-02');

// 获取特定参数的值
const from = params.get('from'); // "reduce"
const endTime = params.get('endTime'); // "2023-12-02"

// 添加新的参数
params.append('newParam', 'value');
console.log(params.toString()); // "from=reduce&endTime=2023-12-02&newParam=value"

// 修改参数的值
params.set('from', 'update');
console.log(params.toString()); // "from=update&endTime=2023-12-02&newParam=value"

// 删除参数
params.delete('endTime');
console.log(params.toString()); // "from=update&newParam=value"

Guess you like

Origin blog.csdn.net/qq_41867900/article/details/134748947