Would it be possible to detect if a string has an image in it. For example,
‘This is an image, talkwalker.com/images/2020/blog-headers/image-analysis.png’.
Then put this image into an
<img src={stringsource} />
And also keep the previous text that was there.
For example, i tried doing something like
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)}>`)
But this is a static and not very good solution because it only works for images ending in png and they must start in http, or else the source will be invalid.
You may use regex to replace all the image urls to image tags:
Regex
(?:https?|ftp):\/\/
starts withhttps://
,http://
orftp://
[\S]*
with anything but not space in between\.(?:png|jpe?g|gif|svg|webp)
ends with.png
,.jpg
,.jpeg
,.gif
,.svg
or.webp
Substitution
$&
means the matching text. It’s the image url in this case.Edit
As an addition, if you want to replace the non-image url to
<p>
tag, you may use the following regex:Basically it makes two group, one is the normal text, the other is image url.
You may replace them accordingly like this:
Try this bro..