Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将URL转换为驱动直接链接,并使用正则表达式将其显示为图像_Javascript_Regex - Fatal编程技术网

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对不起,我粘贴了错误的链接。我是说是的那太完美了