Skip to content

Instantly share code, notes, and snippets.

@jwhb
Last active October 2, 2018 13:14
Show Gist options
  • Save jwhb/73cd34dabf6c4c893b0e4f5fcb9d9d92 to your computer and use it in GitHub Desktop.
Save jwhb/73cd34dabf6c4c893b0e4f5fcb9d9d92 to your computer and use it in GitHub Desktop.
IP address octet manipulation with regex
// manipulate octets of IP address with Javascript regular expressions
var regex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})(\/[1-3]?\d)$/;
var ip = '169.254.0.17/30';
var octet4 = ip.match(regex)[2] - 1; // match and manipulate octet
var ip2 = ip.replace(regex, '$1' + octet4 + '$3'); // reassemble IP
console.log(ip2); //169.254.0.16/30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment