0

I search to detect in a string if the content is just a text or if it's an image URL. I base my detection with the filetype, but I don't know how to detect multiple file types…

var wrapper = (content.indexOf(".jpg", ".jpeg", ".gif", ".png", ".bmp") != -1)
                ? '<img src="' + content + '" />'
                : '<span>' + content + '</span>';

I know this syntax for indexOf is wrong, but in an ideal, that's what I search!

0

2 Answers 2

1

I would go with a cleaner solution - no slice/indexOf or anything like that involved: It tests all elements of the ext array against the content and returns the elements, which match. Since there should be only one match, you just need to check the first element.

var content = "/test.png",
    ext = [".jpg", ".jpeg", ".gif", ".png", ".bmp"],
    res,wrapper;

res = ext.filter(function(el){return content.match(el)});

wrapper = res[0] ? '<img src="'+content+'" />' : '<span>'+content+'</span>';

See Array.prototype.filter on MDN for more explanation. As with Fabrizio's solution this solution might break too, if you have filenames with several . /test.png.jpg (whatever the reason for that might be).

Sign up to request clarification or add additional context in comments.

1 Comment

well yes, it should;) However, same as with indexOf you need to be careful with compatibility - it's supported from IE9 on, but you can use the Shim mentioned in the MDN article for older IE versions.
1

just use indexOf over an array

var wrapper = ([".jpg", ".jpeg", ".gif", ".png", ".bmp"].indexOf(content.slice(-4)) > -1)
                ? '<img src="' + content + '" />'
                : '<span>' + content + '</span>';

content.slice(-4) return last 4 characters of content

On older browser you will need to use a polyfill for indexOf,
see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

7 Comments

this will not work, since content is not the file extension but the whole uri.
@Christoph just sliced the string to get last 4 characters
Yay! Exactly that. It was too simple but I don't know this possibility. Thank you!
content.slice(-4) -> .jpeg = "meeeeep"
".jpeg".indexOf('jpeg'); works anyway; or use a regular expression to match a substring from last .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.