Skip to content Skip to sidebar Skip to footer

Javascript Regex Matching Is Ignoring Literal Dot

I'm trying to match all anchors on a page that link to files with certain extensions, but the code is also catching cases where the URL ends with the extension text, but doesn't co

Solution 1:

As you're using the RegExp constructor, you're passing a string to build the regex. Your backslash to escape the dot in the expression is being eaten as an escapement in the string. The solution is to escape the dot with a double backslash:

var matcher = new RegExp(".*\\.(" + imageExtensions + ")$");

Now the slash is escaped in the string, letting it make it through the parser into the RegExp constructor to escape the dot.


Solution 2:

Another version of your code :)

var a = document.getElementsByTagName("A");
var pattern = /^(http:\/\/)?(.*)\.(jpg|jpeg|png|gif|svg)$/gi;

for(var i = 0; i < a.length; i++){
    if(a[i].href.match(pattern))
        alert(a[i].href);
}

Post a Comment for "Javascript Regex Matching Is Ignoring Literal Dot"