javascript,删除参数从youtube链接,在字符串中

6ie5vjzr  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(117)

嗨我有一个字符串包含几个youtube链接

test test test
https://youtu.be/G7KNmW9a75Y?list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD
https://www.youtube.com/watch?v=JlOZR5OwS-8&list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD&index=4
test test test

它是可能的清理youtube链接从他们的参数,并使他们成为;https://youtu.be/G7KNmW9a75Yhttps://www.youtube.com/watch?v=JlOZR5OwS-8
完成整个字符串

test test test
https://youtu.be/G7KNmW9a75Y
https://www.youtube.com/watch?v=JlOZR5OwS-8
test test test

非常感谢提供解决方案的人
我用这个

'test test test  youtu.be/G7KNmW9a75Y?list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD  youtube.com/watch?v=JlOZR5OwS-8&list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD&index=4 test test test'.replace(/<[^>]*>?/gm, '').replace('https:&#47;/'+videoid[0], "");

但它不会提取完整的链接以便使用replace,并将其从文本中删除

kwvwclae

kwvwclae1#

一般来说,要从"www.example.com"中取出"www.example.com",需要使用new URL(): https://youtu.be/G7KNmW9a75Y " out of " https://youtu.be/G7KNmW9a75Y?list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD " you need to use new URL() :
let u = new URL('https://youtu.be/G7KNmW9a75Y?list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD')${u.origin}${u.pathname}//" www.example.com "〈--您的答案https://youtu.be/G7KNmW9a75Y" <-- your answer
完整代码:

const myStr =
        "test test test https://youtu.be/G7KNmW9a75Y?list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD https://www.youtube.com/watch?v=JlOZR5OwS-8&list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD&index=4 test test test";

      const result = myStr
        .split(" ")
        .map((str) => {
          if (str.match(/\bhttps?:\/\/\S+/gi)) {
            let u = new URL(
              "https://youtu.be/G7KNmW9a75Y?list=PL08MW4hWrm0I5BMN-Z_r8dqRdNTyuyRaD"
            );
            return `${u.origin}${u.pathname}`;
          }

          return str;
        })
        .join("\r\n");

      console.log("result", result); // I noticed that the result of the `map()` fn should be stored in variable otherwise strings won't be placed in new lines

相关问题