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

83
Vistas
Javascript find and replace text by its position in the text

If I have this string

"Something [10], Something else [10].\nBla bla bla [Not always a number].";

Considering that […] identifies a special element that can be modified,

How would you write a function to have the following result?

var findReplaceElemByPosition = function(delimiters,position,new_value){
    //find all the substrings delimited by the *delimimters*
    //select only the one in a certain *position*
    //replace the old value with the *new_value*
}
var myStrangeString = "Something[10], Something else [10].\nBla bla bla [Not always a number].";
myTransformedString = findReplaceElemByPosition("[]",0,20);
myTransformedString = findReplaceElemByPosition("[]",1,21);
myTransformedString = findReplaceElemByPosition("[]",2,"sometimes just a string");
// expected: myTransformedString = "Something[20], Something else [21].\nBla bla bla [sometimes just a string]."

I found a solution by adding spaces before and after delimiters and splitting the text in an array, but I wonder if there is a more elegant (and professional) solution.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

given an array of inputs like so:

const replacments = [
  20,
  21,
  'some string'
]

you can easily replace all the string occurances by using the callback function of replace method using regexp.

function run(string, replacements) {
  const replaceBy = replacements.slice() // just to be safe
  return string.replace(/\[[^\]]*\]/g, (original) => {
    if (replaceBy.length) {
      return `[${replaceBy.shift()}]`
    }
    return original
  })
}

This function can be run as:

const string = 'Something[10], Something else [10].\nBla bla bla [Not always a number].'
const replacements = [20, 21, 'sometimes just a string']
run(string, replacements)
// returns 'Something[20], Something else [21].\nBla bla bla [sometimes just a string].'

It should now be a matter of juggling with the regex to also make the delimiter a parameter, for which you need to use new RegExp, properly escape every special character and also inside the replacer function re-wrap it with the right delimiter.

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