Osman Osman - 6 months ago 8
Javascript Question

How to check if an image URL has been inputted into a Prompt - JavaScript

$(function() {
$(".upload").click(function() {
link = prompt("Paste a background image url");
if (link == null) {
return;
}
else {
div = document.createElement('div');
$(div).addClass("images").html('<img src="' + link + '">');
$(".display").append(div);
}
});
});


Above is the code that I am currently using which asks the user to input an Image URL of which a new div is created with the inputted image within.

If the user inputs a bit of text (or something that isn't an image URL), the div would still be created though the image tag would read:


How do I check to see if the user inputs an image URL?

Answer

You COULD just do:

 var extension = id.substr(link.length - 3); // get last 3 chars from the string
 if ((extension == "bmp") || (extension == "png") || ... you get the idea ) {
 do right stuff
 else
 do wrong stuff

But, you have to take into consideration before displaying the link, that it could also be trying do some XSS, so take the proper considerations