Split IP and port in JavaScript with regular expressions

We recently did some improvements on the elmah.io UI making IPs clickable. We've had automatic detection of IPs for a while but it always bugged me that the regex that we had didn't caught IP addresses with a port number (typically logged by ASP.NET MVC and similar):

127.0.0.1:80

The solution was an improved piece of JavaScript to detect this that I'm sharing in hope of helping others with a similar challenge:

function resolveIP(data) {
    if (data) {
        if(data.match(/^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)(?:\:(?:\d|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/g)) {
            if(data.match(/:/g)) {
                var split = data.split(':');
                return split[0];
            }
            return data;
        }
    }
    return null;
}

You can find all sorts of regex matching IP addresses on the web. The regex above also support including a port number as seen in the example above. If the data value matches the regex, we return the IP part.

Features steps
We monitor your websites

We monitor your websites

We monitor your websites for crashes and availability. This helps you get an overview of the quality of your applications and to spot trends in your releases.

We notify you

We notify you

We notify you when errors starts happening using Slack, Microsoft Teams, mail or other forms of communication to help you react to errors before your users do.

We help you fix bugs

We help you fix bugs

We help you fix bugs quickly by combining error diagnostic information with innovative quick fixes and answers from Stack Overflow and social media.

See how we can help you monitor your website for crashes Monitor your website