File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -171,6 +171,52 @@ function handleFiles(files) {
171171
172172上面代码中,一旦图片加载成功以后,为本地文件生成的临时网址就没用了,于是可以在` img.onload ` 回调函数里面,通过` URL.revokeObjectURL() ` 方法释放资源。
173173
174+ ### URL.canParse()
175+
176+ ` URL.canParse() ` 用来检测一个字符串是否为有效 URL,它返回一个布尔值。
177+
178+ ``` javascipt
179+ URL.canParse(url)
180+ URL.canParse(url, base)
181+ ```
182+
183+ ` URL.canParse() ` 可以接受两个参数。
184+
185+ - ` url ` :字符串或者对象(比如` <a> ` 元素的 DOM 对象),表示 URL。
186+ - ` base ` :字符串或者 URL 实例对象,表示 URL 的基准位置。它是可选参数,当第一个参数` url ` 为相对 URL 时,会使用这个参数,计算出完整的 URL,再进行判断。
187+
188+ ``` javascript
189+ URL .canParse (" https://developer.mozilla.org/" ) // true
190+ URL .canParse (" /en-US/docs" ) // false
191+ URL .canParse (" /en-US/docs" , " https://developer.mozilla.org/" ) // true
192+ ```
193+
194+ 上面示例中,如果第一个参数是相对 URL,这时必须要有第二个参数,否则返回` false ` 。
195+
196+ 下面的示例是第二个参数为 URL 实例对象。
197+
198+ ``` javascript
199+ let baseUrl = new URL (" https://developer.mozilla.org/" );
200+ let url = " /en-US/docs" ;
201+
202+ URL .canParse (url, baseUrl) // true
203+ ```
204+
205+ 该方法内部使用` URL() ` 构造方法相同的解析算法,因此可以用` URL() ` 构造方法代替。
206+
207+ ``` javascript
208+ function isUrlValid (string ) {
209+ try {
210+ new URL (string);
211+ return true ;
212+ } catch (err) {
213+ return false ;
214+ }
215+ }
216+ ```
217+
218+ 上面示例中,给出了` URL.canParse() ` 的替代实现` isUrlValid() ` 。
219+
174220## 实例方法
175221
176222### toString()
You can’t perform that action at this time.
0 commit comments