5

I would like to know how can I detect an image in a string with JavaScript. For example, I have an input type text that has the following value, "Hey check this out https://exmaple.com/image.jpg" I want to wrap 'https://exmaple.com/image.jpg' in an tag so it can show the image right away in my site. Thank you, I tried using the split function in JavaScript but I don't know how to detect the image extension in the string.

PixelAcorn
  • 494
  • 8
  • 26

4 Answers4

7

Use lastIndexOf()

var str = "https://example.com/image.jpg";
var dotIndex = str.lastIndexOf('.');
var ext = str.substring(dotIndex);

Fiddle

Zword
  • 6,605
  • 3
  • 27
  • 52
2
var str = "https://example.com/image.jpg";
var extArray = str.split(".");
var ext = extArray[extArray.length - 1];

Try this.

function searchText(text)
{
  var arr = text.match("/(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/");
  for (var i=0; i<arr.length; i++)
  {
    //Make tags where 'arr[i]' is your url. 
  }
}
Mark
  • 3,224
  • 2
  • 22
  • 30
2

You'd probably want to use a regular expression like the following in order to find any image type, and make sure you're not returning other junk that you don't want. E.g.

'https://exmaple.com/image.jpg'.match(/[^/]+(jpg|png|gif)$/)
-> ["image.jpg", "jpg"]
Willy
  • 1,055
  • 8
  • 23
0

HINT: (Please use logic based on your needs) you have to split string somehow based on your condition and check if the string has . or something

var a = "Hey check this out https://exmaple.com/image.jpg";
var text = a.split(' '); 

if text array has your condition then assign to variable filename

if(jQuery.inArray(".", text)!==-1) { //i dont prefer only .
filename = text[jQuery.inArray(".", text)];
}

separate the extension

function getExt(filename)
{
    var ext = filename.split('.').pop();
    if(ext == filename) return "";
    return ext;
}
Venkat Reddy
  • 1,046
  • 1
  • 8
  • 13