为什么使用anchor.href属性来处理url [英] Why use anchor.href property to process url

查看:71
本文介绍了为什么使用anchor.href属性来处理url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天发现了以下代码:

I've found the following code today:

var baseHref = document.createElement('a');
baseHref.href = this.baseURL;
baseHref = baseHref.pathname;

其中 this.baseURL 是字符串。

似乎它利用了设置 href pathname 被读取。这只是一个假设。这个功能是什么?或者其他用途是什么?

It seems that it takes advantage of some conversion functionality that is perform when href is set or pathname is read. It's just an assumption. What is this functionality? Or what other uses can be?

推荐答案

创建锚点并传入URL,利用解析器中内置的浏览器对于URL,可以很容易地返回URL的不同部分,没有正则表达式或字符串操作。

Creating an anchor, and passing in an URL, takes advantage of the browsers built in parser for URL's, so different parts of the URL can be returned easily, with no regular expressions or string manipulation.

路径名是......好吧,协议和主机名之后的路径名等。

The pathname is ... well, the pathname after the protocol and hostname etc.

一个小例子,其中一些部分可以这样返回

A small example, with some of the parts that can be returned this way

var baseHref = document.createElement('a');
baseHref.href = 'https://www.stackoverflow.com:3333/page/that/goes/somewhere?querystring=test#hash';

console.log('protocol    : ', baseHref.protocol);
console.log('host        : ', baseHref.host);
console.log('hostname    : ', baseHref.hostname);
console.log('port        : ', baseHref.port);
console.log('pathname    : ', baseHref.pathname);
console.log('querystring : ', baseHref.search);
console.log('hash        : ', baseHref.hash);

这真的只是一个解密的好方法URL使用浏览器。

This is really just a neat trick to parse URL's using the browser.

这篇关于为什么使用anchor.href属性来处理url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆