You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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=54 in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:24:24