Skip to content

Commit a3884e0

Browse files
committed
feat(utils): add isUrl fun
1 parent 0fca27b commit a3884e0

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

src/utils/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
export * from './is';
22
export * from './rect';
33

4+
/** 空方法 */
5+
export const noop = () => {};
46
export const now = () => Date.now();
57
export const timestamp = () => +Date.now();

src/utils/is.ts

+40-3
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,46 @@ export const isString = (val: unknown): val is string => typeof val === 'string'
1616
export const isWindow = (val: any): val is Window =>
1717
typeof window !== 'undefined' && toString.call(val) === '[object Window]';
1818

19-
/** 空方法 */
20-
export const noop = () => {};
21-
2219
/** 判断是否是IOS系统 */
2320
export const isIOS =
2421
isClient && window?.navigator?.userAgent && /iP(ad|hone|od)/.test(window.navigator.userAgent);
22+
23+
const protocolAndDomainRE = /^(?:\w+:)?\/\/(\S+)$/;
24+
25+
const localhostDomainRE = /^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/;
26+
const nonLocalhostDomainRE = /^[^\s\.]+\.\S{2,}$/;
27+
28+
/**
29+
* 检查字符串是否是 url
30+
*
31+
* @param value 要检查的值
32+
* @returns `value` 是 Url 返回 `true`,否则返回 `false`
33+
* @example
34+
* ```ts
35+
* isUrl('https://www.baidu.com') // => true
36+
* ```
37+
*/
38+
export default function isUrl(value: string) {
39+
if (!isString(value)) {
40+
return false;
41+
}
42+
43+
const match = value.match(protocolAndDomainRE);
44+
if (!match) {
45+
return false;
46+
}
47+
48+
const everythingAfterProtocol = match[1];
49+
if (!everythingAfterProtocol) {
50+
return false;
51+
}
52+
53+
if (
54+
localhostDomainRE.test(everythingAfterProtocol) ||
55+
nonLocalhostDomainRE.test(everythingAfterProtocol)
56+
) {
57+
return true;
58+
}
59+
60+
return false;
61+
}

0 commit comments

Comments
 (0)