Javascript 函数 - 如果 (scriptTag.src.match

Javascript functions - if (scriptTag.src.match

我有这个用于 YouTube 视频的代码。

if (scriptTag.src.match(/(youtube|youtu|)\.(com|be)\/((watch\?v=([-\w]+))|(projects\/([-\w]+)\/([-\w]+))|([-\w]+))/)) { 

我想改变的是例子:

scriptTag.src.match any url

所以我想使用任何 url 或短代码示例来实现功能:scriptTag.src.match [my wp shortcode]

我希望你能理解我想做的事情,我希望能得到帮助谢谢。

如果你想检查给定的 url 是否与 YouTube 或 Vimeo 相关联,那么你可以简单地使用字符串的 startsWith 方法。

假设 url1url2url3 等同于 scriptTag.src,它们正在考虑您已链接的代码。在这种情况下,您可以像这样简单地编写一个验证函数。

function checkUrl(url) {
  if (url.startsWith('https://www.youtube.com') ||
      url.startsWith('https://vimeo.com')) {
    return true;
  }
  return false;
}

这里是显示该函数用法的片段。

const url1 = 'https://www.youtube.com/whatever';
const url2 = 'https://vimeo.com/whatever';
const url3 = 'http://wrongSource.com'

function checkUrl(url) {
  if (url.startsWith('https://www.youtube.com') ||
      url.startsWith('https://vimeo.com')) {
    return true;
  }
  return false;
}

if (checkUrl(url1)) {
  console.log('url1 is valid');
  // do some stuff
} else {
  console.log('url1 is not valid');
  // do nothing
}

if (checkUrl(url2)) {
  console.log('url2 is valid');
  // do some stuff
} else {
  console.log('url2 is not valid');
  // do nothing
}

if (checkUrl(url3)) {
  console.log('url3 is valid');
  // do some stuff
} else {
  console.log('url3 is not valid');
  // do nothing
}