簡體   English   中英

檢查字符串是否包含圖像

[英]Checking if a string contains a image

是否可以檢測字符串中是否包含圖像。 例如,“這是一張圖片,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)}>`)

但這是一個 static 並且不是很好的解決方案,因為它僅適用於以 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*)*)?)

基本上它分為兩組,一組是普通文本,另一組是圖像 url。

您可以像這樣相應地替換它們:

 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);

試試這個兄弟。。

const msgstring = 'Hello how are you, check out this image 
   https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png'
   var test = (/\.(gif|jpg|jpeg|tiff|png)$/i).test(msgstring)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM