Checking if a string contains a image

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.

2 thoughts on “Checking if a string contains a image”

  1. You may use regex to replace all the image urls to image tags:

    Regex

    /(?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)/gi
    
    • (?:https?|ftp):\/\/ starts with https://, http:// or ftp://
    • [\S]* with anything but not space in between
    • \.(?:png|jpe?g|gif|svg|webp) ends with .png, .jpg, .jpeg, .gif, .svg or .webp

    Substitution

    <img src="$&" />
    
    • $& means the matching text. It’s the image url in this case.

    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)/g;
    
    const result = msgstring.replace(imageRegex, '<img src="$&" />');
    
    console.log(result);

    Edit

    As an addition, if you want to replace the non-image url to <p> tag, you may use the following regex:

    ((?:(?!(?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)).)+)|((?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp))
    

    Basically it makes two group, one is the normal text, the other is image url.

    You may replace them accordingly like this:

    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 Bye';
    
    const imageRegex = /((?:(?!(?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp)).)+)|((?:https?|ftp):\/\/[\S]*\.(?:png|jpe?g|gif|svg|webp))/g;
    
    const result = msgstring.replace(imageRegex, (_, text, img) => text ? `<p>${text.trim()}</p>` : `<img src="${img}" />`);
    
    console.log(result);
    Reply
  2. Try this bro..

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

Leave a Comment