Javascript 将URL转换为驱动直接链接,并使用正则表达式将其显示为图像
我有一块多行文字: 输入:Javascript 将URL转换为驱动直接链接,并使用正则表达式将其显示为图像,javascript,regex,Javascript,Regex,我有一块多行文字: 输入: 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
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
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
运行js脚本时,必须将其转换为html,并将直接驱动链接转换为img标记
预期输出:
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
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
但是我如何将
{{image:…}}
替换为img
标记呢?您可以使用两个捕获组来保存要保留的部分,并匹配您不想保留的{image:
、/file/d/
和}
{{image:(https?:\/\/[^\/]+)\/file\/d\/([^\/]+).*?}}
逐字匹配{{image:
Capturegroup 1(
匹配协议,后跟除https?:\/\/[^\/]+
/
关闭第1组)
匹配\/file\/d\/
/file/d/
捕获第2组(
匹配除[^\/]+
/
关闭第2组)
尽可能少地匹配任何字符*?
逐字匹配}
const str=`这里还有一些文本
{{图片:https://drive.google.com/file/d/1jYbEcuN-EMNkc0ELeVLveNJiaiuQt4XK/view?usp=sharing}}
这里有一些文字
{{图片:https://drive.google.com/file/d/2jYbEcuN-EMNkc0ELeVLveNJiaiuQt4XK/view?usp=sharing}}
这里有更多的文字`;
const result=str.replace(/{image:(https?:\/\/[^\/]+)\/file\/d\/([^\/]+).}}/g,```);
控制台日志(结果)代码>你的代码不会改变驱动器的URL,请看一下前后src标签的链接,我要求的是在一个regex@CodeGuy我明白了,我会更新代码的。谢谢@第四只鸟,id将保持不变。url被转换成一个直接的URL@CodeGuy对不起,我粘贴了错误的链接。我是说是的那太完美了