javascript - 将 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
标签?
解决方案
您可以为要保留的部分使用 2 个捕获组,并匹配{{image:
您/file/d/
不想}}
保留的部分。
{{image:(https?:\/\/[^\/]+)\/file\/d\/([^\/]+).*?}}
{{image:
从字面上匹配(
捕获组 1https?:\/\/[^\/]+
匹配协议后跟任何字符,除了/
)
关闭组 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);
推荐阅读
- r - 查找 wilcoxon 符号秩检验的拒绝区域
- swift - 我们如何在 swift 中为 kCGPDFContextAllowsCopying 设置 CFString 的 false 值
- r - R 2d图中的计数比率
- python - 我的图像在 django 中显示为损坏的文件
- reactjs - .Net Core 3.1 SPA React 应用程序不提供 Hangfire 仪表板/Swagger 在生产中
- javascript - 折叠具有位置的元素:绝对
- hive - 基于 S3 中的 Parquet 文件在 Athena 中创建外部表时如何重命名列?
- kubernetes - 可以在 prestop 挂钩中使用的有效 http 请求是什么?
- python - 我怎样才能从这个函数中得到归一化矩阵?
- sql-server - 如何使用 SQL Server 和 AWS RSD 读取 XML 文件?