0
# URL Processing
1
2
URL validation and video ID extraction supporting all YouTube URL formats including shortened URLs, embed links, and mobile URLs. Provides robust parsing with comprehensive error handling.
3
4
## Capabilities
5
6
### Video ID Validation
7
8
Validates whether a string matches YouTube's video ID format.
9
10
```javascript { .api }
11
/**
12
* Validates if string matches YouTube video ID format
13
* @param {string} id - String to validate as video ID
14
* @returns {boolean} - Whether string is valid video ID format
15
*/
16
function validateID(id);
17
```
18
19
YouTube video IDs are exactly 11 characters long and contain only alphanumeric characters, hyphens, and underscores.
20
21
**Usage Examples:**
22
23
```javascript
24
// Valid video IDs
25
console.log(ytdl.validateID('aqz-KE-bpKQ')); // true
26
console.log(ytdl.validateID('dQw4w9WgXcQ')); // true
27
28
// Invalid video IDs
29
console.log(ytdl.validateID('too-short')); // false
30
console.log(ytdl.validateID('too-long-id')); // false
31
console.log(ytdl.validateID('invalid@chars')); // false
32
console.log(ytdl.validateID('')); // false
33
```
34
35
### URL Validation
36
37
Validates whether a URL can be parsed to extract a YouTube video ID.
38
39
```javascript { .api }
40
/**
41
* Validates if URL can be parsed to extract video ID
42
* @param {string} url - URL to validate
43
* @returns {boolean} - Whether URL is valid YouTube URL
44
*/
45
function validateURL(url);
46
```
47
48
**Usage Examples:**
49
50
```javascript
51
// Valid YouTube URLs
52
console.log(ytdl.validateURL('https://www.youtube.com/watch?v=aqz-KE-bpKQ')); // true
53
console.log(ytdl.validateURL('https://youtu.be/aqz-KE-bpKQ')); // true
54
console.log(ytdl.validateURL('https://m.youtube.com/watch?v=aqz-KE-bpKQ')); // true
55
56
// Invalid URLs
57
console.log(ytdl.validateURL('https://example.com/video')); // false
58
console.log(ytdl.validateURL('https://youtube.com/invalid')); // false
59
console.log(ytdl.validateURL('not-a-url')); // false
60
```
61
62
### Extract Video ID from URL
63
64
Extracts the video ID from various YouTube URL formats.
65
66
```javascript { .api }
67
/**
68
* Extracts video ID from YouTube URL
69
* @param {string} url - YouTube URL
70
* @returns {string} - 11-character video ID
71
* @throws {Error} - If URL is invalid or no video ID found
72
* @throws {TypeError} - If extracted ID doesn't match expected format
73
*/
74
function getURLVideoID(url);
75
```
76
77
**Supported URL Formats:**
78
79
- `https://www.youtube.com/watch?v=VIDEO_ID`
80
- `https://m.youtube.com/watch?v=VIDEO_ID`
81
- `https://youtu.be/VIDEO_ID`
82
- `https://www.youtube.com/v/VIDEO_ID`
83
- `https://www.youtube.com/embed/VIDEO_ID`
84
- `https://www.youtube.com/shorts/VIDEO_ID`
85
- `https://music.youtube.com/watch?v=VIDEO_ID`
86
- `https://gaming.youtube.com/watch?v=VIDEO_ID`
87
88
**Usage Examples:**
89
90
```javascript
91
// Standard watch URLs
92
const id1 = ytdl.getURLVideoID('https://www.youtube.com/watch?v=aqz-KE-bpKQ');
93
console.log(id1); // 'aqz-KE-bpKQ'
94
95
// Shortened URLs
96
const id2 = ytdl.getURLVideoID('https://youtu.be/dQw4w9WgXcQ');
97
console.log(id2); // 'dQw4w9WgXcQ'
98
99
// Embed URLs
100
const id3 = ytdl.getURLVideoID('https://www.youtube.com/embed/aqz-KE-bpKQ');
101
console.log(id3); // 'aqz-KE-bpKQ'
102
103
// Mobile URLs
104
const id4 = ytdl.getURLVideoID('https://m.youtube.com/watch?v=aqz-KE-bpKQ&t=30s');
105
console.log(id4); // 'aqz-KE-bpKQ'
106
107
// Music URLs
108
const id5 = ytdl.getURLVideoID('https://music.youtube.com/watch?v=aqz-KE-bpKQ&list=PLrAXtmRdnEQy4Qg8SU5U6QP0X3bL5T8lN');
109
console.log(id5); // 'aqz-KE-bpKQ'
110
111
// URLs with extra parameters are handled
112
const id6 = ytdl.getURLVideoID('https://www.youtube.com/watch?v=aqz-KE-bpKQ&list=PLxxx&index=1&t=120s');
113
console.log(id6); // 'aqz-KE-bpKQ'
114
```
115
116
### Get Video ID (Flexible)
117
118
Gets video ID from either a URL or validates if the input is already a video ID.
119
120
```javascript { .api }
121
/**
122
* Gets video ID from URL or validates if already an ID
123
* @param {string} str - URL or video ID string
124
* @returns {string} - 11-character video ID
125
* @throws {Error} - If unable to extract valid video ID
126
* @throws {TypeError} - If extracted ID doesn't match expected format
127
*/
128
function getVideoID(str);
129
```
130
131
This is the most flexible function - it handles both URLs and direct video IDs.
132
133
**Usage Examples:**
134
135
```javascript
136
// Works with URLs
137
const id1 = ytdl.getVideoID('https://www.youtube.com/watch?v=aqz-KE-bpKQ');
138
console.log(id1); // 'aqz-KE-bpKQ'
139
140
// Works with direct video IDs
141
const id2 = ytdl.getVideoID('aqz-KE-bpKQ');
142
console.log(id2); // 'aqz-KE-bpKQ'
143
144
// Automatically detects format
145
function processVideo(input) {
146
try {
147
const videoId = ytdl.getVideoID(input);
148
console.log(`Processing video: ${videoId}`);
149
return ytdl.getInfo(videoId);
150
} catch (error) {
151
console.error('Invalid video input:', error.message);
152
}
153
}
154
155
processVideo('https://youtu.be/dQw4w9WgXcQ'); // Works
156
processVideo('dQw4w9WgXcQ'); // Also works
157
processVideo('invalid-input'); // Throws error
158
```
159
160
## URL Format Details
161
162
### Standard YouTube Domains
163
164
Valid domains for query-based URLs:
165
- `youtube.com`
166
- `www.youtube.com`
167
- `m.youtube.com` (mobile)
168
- `music.youtube.com`
169
- `gaming.youtube.com`
170
171
### Path-based URL Patterns
172
173
URLs where the video ID is in the path:
174
- `youtu.be/VIDEO_ID` (shortened)
175
- `youtube.com/embed/VIDEO_ID` (embed)
176
- `youtube.com/v/VIDEO_ID` (old format)
177
- `youtube.com/shorts/VIDEO_ID` (shorts)
178
179
### Query Parameter Handling
180
181
For query-based URLs, the video ID is extracted from the `v` parameter:
182
183
```javascript
184
// All of these extract the same video ID
185
ytdl.getVideoID('https://www.youtube.com/watch?v=aqz-KE-bpKQ');
186
ytdl.getVideoID('https://www.youtube.com/watch?v=aqz-KE-bpKQ&t=30s');
187
ytdl.getVideoID('https://www.youtube.com/watch?list=PLxxx&v=aqz-KE-bpKQ&index=2');
188
ytdl.getVideoID('https://www.youtube.com/watch?feature=youtu.be&v=aqz-KE-bpKQ');
189
```
190
191
## Error Handling
192
193
### Common Errors and Solutions
194
195
```javascript
196
try {
197
const videoId = ytdl.getVideoID(userInput);
198
} catch (error) {
199
if (error.message.includes('Not a YouTube domain')) {
200
console.error('URL is not from YouTube');
201
} else if (error.message.includes('No video id found')) {
202
console.error('URL does not contain a video ID');
203
} else if (error.message.includes('does not match expected format')) {
204
console.error('Video ID format is invalid');
205
} else {
206
console.error('Unknown URL parsing error:', error.message);
207
}
208
}
209
```
210
211
### Input Validation Pattern
212
213
Robust input validation for user-provided URLs or IDs:
214
215
```javascript
216
function sanitizeVideoInput(input) {
217
if (!input || typeof input !== 'string') {
218
throw new Error('Input must be a non-empty string');
219
}
220
221
// Trim whitespace
222
input = input.trim();
223
224
// Check if it looks like a URL
225
if (input.includes('youtube.com') || input.includes('youtu.be')) {
226
// Validate URL format
227
if (!ytdl.validateURL(input)) {
228
throw new Error('Invalid YouTube URL format');
229
}
230
return ytdl.getURLVideoID(input);
231
} else {
232
// Assume it's a video ID
233
if (!ytdl.validateID(input)) {
234
throw new Error('Invalid video ID format');
235
}
236
return input;
237
}
238
}
239
240
// Usage
241
try {
242
const videoId = sanitizeVideoInput(userInput);
243
const info = await ytdl.getInfo(videoId);
244
} catch (error) {
245
console.error('Invalid input:', error.message);
246
}
247
```
248
249
### Batch URL Processing
250
251
Processing multiple URLs with error handling:
252
253
```javascript
254
async function processVideoURLs(urls) {
255
const results = [];
256
257
for (const url of urls) {
258
try {
259
const videoId = ytdl.getVideoID(url);
260
const info = await ytdl.getBasicInfo(videoId);
261
262
results.push({
263
url,
264
videoId,
265
title: info.videoDetails.title,
266
success: true
267
});
268
} catch (error) {
269
results.push({
270
url,
271
error: error.message,
272
success: false
273
});
274
}
275
}
276
277
return results;
278
}
279
280
// Process mixed input
281
const urls = [
282
'https://www.youtube.com/watch?v=aqz-KE-bpKQ',
283
'https://youtu.be/dQw4w9WgXcQ',
284
'invalid-url',
285
'aqz-KE-bpKQ'
286
];
287
288
const results = await processVideoURLs(urls);
289
results.forEach(result => {
290
if (result.success) {
291
console.log(`✓ ${result.title} (${result.videoId})`);
292
} else {
293
console.log(`✗ ${result.url}: ${result.error}`);
294
}
295
});
296
```
297
298
## Integration Patterns
299
300
### URL Normalization
301
302
Normalize different URL formats to a standard format:
303
304
```javascript
305
function normalizeYouTubeURL(input) {
306
const videoId = ytdl.getVideoID(input);
307
return `https://www.youtube.com/watch?v=${videoId}`;
308
}
309
310
// All of these become the same normalized URL
311
console.log(normalizeYouTubeURL('https://youtu.be/aqz-KE-bpKQ'));
312
console.log(normalizeYouTubeURL('https://m.youtube.com/watch?v=aqz-KE-bpKQ'));
313
console.log(normalizeYouTubeURL('aqz-KE-bpKQ'));
314
// All output: https://www.youtube.com/watch?v=aqz-KE-bpKQ
315
```
316
317
### User Input Handling
318
319
Create user-friendly interfaces that accept flexible input:
320
321
```javascript
322
class YouTubeProcessor {
323
async process(input) {
324
try {
325
// Flexible input handling
326
const videoId = ytdl.getVideoID(input);
327
328
console.log(`Processing video ID: ${videoId}`);
329
330
// Check if video exists and is accessible
331
const basicInfo = await ytdl.getBasicInfo(videoId);
332
333
if (basicInfo.videoDetails.isPrivate) {
334
throw new Error('Video is private');
335
}
336
337
return basicInfo;
338
339
} catch (error) {
340
throw new Error(`Failed to process input "${input}": ${error.message}`);
341
}
342
}
343
}
344
```