javascript - 检查字符串是否包含图像
问题描述
是否可以检测字符串中是否包含图像。例如,“这是一张图片,talkwalker.com/images/2020/blog-headers/image-analysis.png”。然后将这张图片放入
<img src={stringsource} />
并保留之前的文本。例如,我尝试做类似的事情
const msgstring = 'Hello how are you, check out this image
https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png'
msgstring.replace(msgstring.slice(msgstring.indexOf('http'), msgstring.indexOf('png')+3),`<img src=${msgstring.slice(msgstring.indexOf('http'), msgstring.indexOf('png')+3)}>`)
但这是一个静态的,不是很好的解决方案,因为它只适用于以 png 结尾的图像并且它们必须以 http 开头,否则源将无效。
解决方案
您可以使用正则表达式将所有图像 url 替换为图像标签:
正则表达式
/(?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)(?:\?\S+=\S*(?:&\S+=\S*)*)?/gi
(?:https?|ftp):\/\/
以https://
,http://
或ftp://
[\S]*
中间没有空格\.(?:png|jpe?g|gif|svg|webp)
以.png
,.jpg
,.jpeg
,.gif
,.svg
或.webp
(?:\?\S+=\S*(?:&\S+=\S*)*)?
查询字符串检测器,如果有的话,包括查询字符串
替代
<img src="$&" />
$&
表示匹配的文本。在这种情况下,它是图像 url。
const msgstring = 'Hello how are you, check out this image https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png';
const imageRegex = /(?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)(?:\?\S+=\S*(?:&\S+=\S*)*)?/g;
const result = msgstring.replace(imageRegex, '<img src="$&" />');
console.log(result);
编辑
另外,如果您想将非图像 url 替换为<p>
标记,您可以使用以下正则表达式:
((?:(?!(?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)).)+)|((?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)(?:\?\S+=\S*(?:&\S+=\S*)*)?)
基本上它分为两组,一组是普通文本,另一组是图片网址。
您可以像这样相应地替换它们:
const msgstring = 'Hello how are you, check out this image https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png Hello how are you, check out this image https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png?alt=media Hello how are you, check out this image https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png?alt=media&test=aaa&a=b Bye';
const imageRegex = /((?:(?!(?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)).)+)|((?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)(?:\?\S+=\S*(?:&\S+=\S*)*)?)/g;
const result = msgstring.replace(imageRegex, (_, text, img) => text ? `<p>${text.trim()}</p>` : `<img src="${img}" />`);
console.log(result);
推荐阅读
- python - 进入另一个 elif 语句时,我的变量刷新为 0
- android - 如何在工具栏片段中居中字符串?
- python - 从 OSX 上可怕的 pip/pip3 混乱中恢复
- kubernetes - 无法使用 k8s master 的 NodePort 访问服务
- flutter - 为什么 TextFormField 的示例不再起作用?
- printf - 如何在ttl语言中使用crlf生成字符串变量
- python - 警告:已安装脚本 pipenv 和 pipenv-resolver
- java - Selenium - 线程“主”java.lang.NoClassDefFoundError 中的异常:org/reactivestreams/Publisher
- c# - 如果这不是真的,Unity 的检查器会在序列化字段上显示“类型不匹配”
- python - 无法关闭正在运行的事件循环 discord.py