JavaScript实现从字符串中提取YouTube视频ID并替换原URL
Solution to Extract YouTube Video IDs from Full URLs
Got it, here's a solid JavaScript solution to strip those full YouTube URLs down to just the video IDs while leaving the rest of your string intact:
Step-by-Step Explanation
We’ll use a regular expression that targets all common YouTube URL formats (watch, embed, youtu.be) preceded by videoid=, captures the unique video ID, and replaces the entire URL with just videoid=[ID].
Code Implementation
function cleanYouTubeVideoIds(inputString) { // Regex to match all YouTube URL formats and capture the video ID const youtubeRegex = /videoid=https?:\/\/(?:www\.youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]+)(?:\?.*)?/g; // Replace each match with "videoid=" plus the captured ID return inputString.replace(youtubeRegex, 'videoid=$1'); } // Example usage const originalString = "pre text videoid=https://www.youtube.com/watch?v=CF1zRWVdDnA videoid=https://www.youtube.com/embed/u4x9YyRnFDE?start=54 videoid=https://youtu.be/loyfGyvpv1o, post text"; const cleanedString = cleanYouTubeVideoIds(originalString); console.log(cleanedString); // Output: "pre text videoid=CF1zRWVdDnA videoid=u4x9YyRnFDE videoid=loyfGyvpv1o, post text"
Key Details
- The regex handles http/https variations, query parameters (like
?start=54in the embed example), and all three common YouTube URL structures. - It only modifies parts of the string that start with
videoid=followed by a valid YouTube URL—all other text remains untouched. - YouTube video IDs are always 11 characters long, composed of letters, numbers, underscores, and hyphens, which the regex captures perfectly.
Edge Case Handling
- If a URL has extra query parameters (like
&t=10s), those get stripped entirely since we only care about the ID. - Invalid YouTube URLs (that don’t follow the standard formats) won’t be modified—so you don’t have to worry about accidental changes to non-URL text.
内容的提问来源于stack exchange,提问作者john_black
相关产品推荐
相关产品推荐

