I have the following code to do a basic IP validation. Actually, it's just academic and I'm using this code to practice using String.replace (intentionally using a poor/loose regex):
let potential_ips = [
'1.2.3.4.5',
'12.34.45.56',
'123.456.789.0',
'1.2.3.4.5.6'
]
var group_num = 0;
function rePlace(m, g1) {
group_num ++;
if (parseInt(g1) > 255) {
return '<invalid>'
} else if (group_num > 4) {
return '<invalid>'
} else {
return m;
}
}
const regex = /(\d{1,3})\.?/g;
for (ip of potential_ips) {
group_num = 0;
ip = ip.replace(regex, rePlace);
console.log('222', ip);
}
What I'm trying to do is when the .replace function is called to keep a running total of the number of times it's been called for that particular string. Currently I'm using a var at the top-level scope, but I'm wondering if there is a sort of cleaner way to do this within the function itself? What would be a better approach to doing this?
You could take a closure over the count and initialize with zero.
const
rePlace = count => m => {
count++;
if (parseInt(m) > 255 || count > 4) return '<invalid>';
return m;
},
regex = /\d+(?=(\.|$))/g,
potential_ips = ['1.2.3.4.5', '12.34.45.56', '123.456.789.0', '1.2.3.4.5.6'];
for (let ip of potential_ips) {
ip = ip.replace(regex, rePlace(0));
console.log('222', ip);
}
The concept here is copied from Nina's answer, but here is one approach where the rePlace function now returns a bound function with an initialized variable to zero (perhaps a bit like Church numerals?)
function rePlace(count) {
return function(m) {
count ++;
return (parseInt(m) > 255 || count > 4) ? '<invalid>' : m;
}
}
const regex = /\d+(?=(\.|$))/g
const potential_ips = ['1.2.3.4.5', '12.34.45.56', '123.456.789.0', '1.2.3.4.5.6'] ;
for (let ip of potential_ips) {
ip = ip.replace(regex, rePlace(0));
console.log('222', ip);
}