首页 > 解决方案 > 将 URL 转换为驱动直接链接并使用正则表达式将其显示为图像

问题描述

我有一个多行文本块:

输入:

Some more text here
{{image:https://drive.google.com/file/d/1jYbEcuN-EMNkc0ELeVLveNJiaiuQt4XK/view?usp=sharing}}
Some text here
{{image:https://drive.google.com/file/d/2jYbEcuN-EMNkc0ELeVLveNJiaiuQt4XK/view?usp=sharing}}
Some more text here

运行 js 脚本时,必须将其转换为带有直接驱动链接到 img 标签标记的 html

预期输出:

 Some more text here
    <img src="https://drive.google.com/uc?export=download&id=1jYbEcuN-EMNkc0ELeVLveNJiaiuQt4XK" />
    Some text here
    <img src="https://drive.google.com/uc?export=download&id=2jYbEcuN-EMNkc0ELeVLveNJiaiuQt4XK" />
    Some more text here

我尝试过:

htmlText = htmlText.replace(/\/file\/d\/(.+)\/(.+)/, "/uc?export=download&id=$1");

但是如何替换{{image: ... }}img标签?

标签: javascriptregex

解决方案


您可以为要保留的部分使用 2 个捕获组,并匹配{{image:/file/d/不想}}保留的部分。

{{image:(https?:\/\/[^\/]+)\/file\/d\/([^\/]+).*?}}
  • {{image:从字面上匹配
  • (捕获组 1
    • https?:\/\/[^\/]+匹配协议后跟任何字符,除了/
  • )关闭组 1
  • \/file\/d\/匹配/file/d/
  • (捕获组 2
    • [^\/]+匹配任何字符的 1 次以上,除了/
  • )关闭组 2
  • .*?尽可能少地匹配任何字符
  • }}从字面上匹配

正则表达式演示

const str = `Some more text here
{{image:https://drive.google.com/file/d/1jYbEcuN-EMNkc0ELeVLveNJiaiuQt4XK/view?usp=sharing}}
Some text here
{{image:https://drive.google.com/file/d/2jYbEcuN-EMNkc0ELeVLveNJiaiuQt4XK/view?usp=sharing}}
Some more text here`;
const result = str.replace(/{{image:(https?:\/\/[^\/]+)\/file\/d\/([^\/]+).*?}}/g, `<img src="$1/uc?export=download&id=$2" />`);
console.log(result);


推荐阅读