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

89
Vistas
Removing specific element from string but only in line that contains another specific element JS

Not sure if I phrase the question correctly so here is an example

let string = "Test text ab/c test
Test t/est
### Test/
Test t/test
Test test"

I'm looking to remove / from only line that contains ### in it so it ends up like this:

Test text ab/c test
Test t/est
### Test
Test t/test
Test test

I assume I can use

mystring.replace(/\/g, '')

But how do I specify that it needs to remove \ only in the line with ###

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

0

You can split on newlines and then join them back again.

let string = `Test text ab/c test
Test t/est
### Test/
Test t/test
Test test
Test// ### test / 
`

const parts = string.split("\n")
  .map(s => s.includes("###") ? s.replace(/\//g, '') : s)
  .join("\n");
console.log(parts);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use

string.replace(/(?<=###.*)\/|\/(?=.*###)/g, '')

The (?<=###.*)\/|\/(?=.*###) regex matches a / char that is either preceded with ### and any zero or more non-line break chars, or followed with zero or more non-line break chars and then ###.

See this JavaScript demo:

let string = "Test text ab/c test\nTest t/est\n### /T/e/s/t/\nTest t/test\nTest test"
console.log(string.replace(/(?<=###.*)\/|\/(?=.*###)/g, ''))

Another solution: split the stirng into lines, then map the resulting array and remove all / chars in the items that includes the ### substring, and then join the string back:

let string = "Test text ab/c test\nTest t/est\n### /T/e/s/t/\nTest t/test\nTest test"
console.log( string.split("\n").map(line => line.indexOf('###') > -1 ? line.replace(/\//g, '') : line).join("\n") )

about 4 years ago · Juan Pablo Isaza Denunciar

0

.replace() the whole segment then return everything but \/ (the \ is prefixed to / in order to escape it.

const str = `
  Test text ab/c test
  Test t/est
  ### Test/
  Test t/test
  Test test`;

const rgx = /(###.+)\//gm;
const sub = `$1`;

console.log(str.replace(rgx, sub));

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