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.
Asked
Active
Viewed 1.3k times
5
-
No that's how you get the extension what i need is to detect it in string and wrap it in a image tag – Sergio Robledo Arango Feb 21 '14 at 21:53
-
OK, I understand now. Retracted close vote that would close as a duplicate! – MikeSmithDev Feb 21 '14 at 22:06
4 Answers
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
-
That would work for the string he provided, but not for `Hey check this out https://exmaple.com/image.jpg it is great`. – MikeSmithDev Feb 21 '14 at 22:08
-
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