首页 > 解决方案 > 检查字符串是否包含图像

问题描述

是否可以检测字符串中是否包含图像。例如,“这是一张图片,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 开头,否则源将无效。

标签: javascriptreactjs

解决方案


您可以使用正则表达式将所有图像 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);


推荐阅读