Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
Concept of a static variable inside a function when called by string.replace

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
}

about 4 years ago · Juan Pablo Isaza Report

0

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);
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!