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.
elmah.io: Error logging and Uptime Monitoring for your web apps
This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.
See how we can help you monitor your website for crashes Monitor your website