Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda