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!

有帮助吗?

解决方案

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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top