EmmyS EmmyS - 7 days ago 5
Javascript Question

Check for a regex string match in a javascript array

I'm writing some client-side validation for our custom CMS. I need to check for any URL containing an image in a text area, and let the user know that they need to use https instead of http.

I've figured out how to search for any URL that starts with http:

$('#template_form').submit(function() {
val = $("#template_data").val();
if (val.match(/http:\/\//)) {
alert("You must set all complete image URLs to be https!");
$("#logError").val("true");
return false;
}
return true;
});


But this will also apply to any regular links that are included. If we could limit this to
<img>
tags it would be simpler, because I could just get the last three characters of the string and do an
indexOf
against an array of image suffixes.

We can't do that, though - an image URL could be included in a custom tag, it could be part of an
alt
parameter, it could be posted as a direct link, or any number of other things. Is there any way to test the regex against an array, or do I need to loop through the array and run a
String.indexOf
against each element separately?

Ideally, I'd do something like this:

suffixes = [".jpg", ",jpeg", ".png", ".gif", ".tiff", ".bmp"];
if (val.match(/http:\/\//)) && suffixes.indexOf(**some kind of regex**) {
alert("You must set all complete image URLs to be https!");
$("#logError").val("true");
return false;
}


but I can't quite figure out what that regex would be.

Answer

You can build a regex using your image extensions:

var suffixes = ["jpg", "jpeg", "png", "gif", "tiff", "bmp"];

var re = new RegExp('http://[^>\\s]+?\.(?:' + suffixes.join('|') + ')');

if (re.test(val)) {
    alert("You must set all complete image URLs to be https!");
    $("#logError").val("true");
    return false;
}

JSFiddle

Code Demo

var val = '<img src="http://www.google.com/test.jpg" />';
var suffixes = ["jpg", "jpeg", "png", "gif", "tiff", "bmp"];
var re = new RegExp('http://[^>\\s]+?\.(?:' + suffixes.join('|') + ')');

console.log(re.test(val));