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

265
Vistas
What is the best way to replace 2 possible strings with another string?

If the string starts with either foo.com or bar.me replace with baz.co. Is this the most efficient / concise way?

string1.replace('foo.com', 'baz.co').replace('bar.me', 'baz.co')

We could have an array of strings: ['foo.com', 'bar.me']

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

0

You can use a regular expression:

string1.replace(/foo\.com|bar\.me/, 'baz.co')

"Starts with" would require to anchor the expression:

string1.replace(/^(foo\.com|bar\.me)/, 'baz.co')
about 4 years ago · Juan Pablo Isaza Denunciar

0

I understood you question. You would like to replace a couple of strings in an array with "baz.co". You have two arrays. 1) array with multiple strings. 2) array with string which you will replace (needle). And a string which you use for the replacement.

const arr = ['foo.com', 'bar.me', 'not.re'];
const nee = ['foo.com', 'bar.me']
const rep = 'baz.co'
const n = [];

arr.forEach(i => { 
  n.push( nee.includes(i) ? rep : i);
})

console.log(n)

about 4 years ago · Juan Pablo Isaza Denunciar

0

I would suggest the solution of Felix Kling.

A more generalized way to solve such "chained" operations (In case that those can't be expressed with a RegExp) would be to use the Array.reduce functionality:

let string1 = 'bar.me.test'

string1 = ['foo.com', 'bar.me'].reduce((previousValue, valueFromArray) => {
  return previousValue.replace(valueFromArray, 'baz.co')
}, string1);

console.log(string1)

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