Skip to content

Commit e72e3ca

Browse files
authored
Implement URL.canParse() (#491)
1 parent 04caa34 commit e72e3ca

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

js/URL.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,14 @@ whatwgUrl.revokeObjectURL = function revokeObjectURL(url) {
5252
// Do nothing.
5353
};
5454

55+
whatwgUrl.canParse = function canParse(url, base) {
56+
try {
57+
// eslint-disable-next-line no-new
58+
new URL(url, base);
59+
return true;
60+
} catch {
61+
return false;
62+
}
63+
};
64+
5565
export const URL = whatwgUrl;

js/__tests__/URL-test.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import {URL} from '../URL';
22

3-
describe('URL', function () {
3+
describe('URL', () => {
44
it('should pass Mozilla Dev Network examples', () => {
55
const a = new URL('/', 'https://developer.mozilla.org');
66
expect(a.href).toBe('https://developer.mozilla.org/');
@@ -61,4 +61,22 @@ describe('URL', function () {
6161
'https://facebook.github.io/react-native/img/header_logo.png',
6262
);
6363
});
64+
65+
describe('URL.canParse', () => {
66+
it('should return true for valid URLs', () => {
67+
expect(URL.canParse('https://example.com')).toBe(true);
68+
expect(URL.canParse('ftp://example.com')).toBe(true);
69+
expect(URL.canParse('mailto:example@example.com')).toBe(true);
70+
expect(
71+
URL.canParse('/en-US/docs', 'https://developer.mozilla.org/'),
72+
).toBe(true);
73+
});
74+
75+
it('should return false for invalid URLs', () => {
76+
expect(URL.canParse('invalid-url')).toBe(false);
77+
expect(URL.canParse('http://')).toBe(false);
78+
expect(URL.canParse('ftp://')).toBe(false);
79+
expect(URL.canParse('//', 'https://developer.mozilla.org/')).toBe(false);
80+
});
81+
});
6482
});

0 commit comments

Comments
 (0)