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

161
Vistas
Find and replace string text between two other string texts JS

I'm trying to find and replace a word in a string

Example:

let string = 
`
Title: Hello World
Authors: Michael Dan
`

I need to find the Hellow World and replace with whatever I want, here is my attempt:

const replace = string.match(new RegExp("Title:" + "(.*)" + "Authors:")).replace("Test")
about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

When you replace some text, it is not necessary to run String#match or RegExp#exec explicitly, String#replace does it under the hood.

You can use

let string = "\nTitle: Hello World\nAuthors: Michael Dan\n"
console.log(string.replace(/(Title:).*(?=\nAuthors:)/g, '$1 Test'));

The pattern matches

  • (Title:) - Group 1: Title: fixed string
  • .* - the rest of the line, any zero or more chars other than line break chars, CR and LF (we need to consume this text in order to remove it)
  • (?=\nAuthors:) - a positive lookahead that matches a location that is immediately followed with an LF char and Authors: string.

See the regex demo.

If there can be a CRLF line ending in your string, you will need to replace (?=\nAuthors:) with (?=\r?\nAuthors:) or (?=(?:\r\n?|\n)Authors:).

about 4 years ago · Santiago Gelvez Denunciar

0

You might be better off converting to an object first and then just defining the title property:

let string = 
`
Title: Hello World
Authors: Michael Dan
`

const stringLines = string.split('\n');
let stringAsObject = {};

stringLines.forEach(
  (line) => {
    if (line.includes(':')) {
      stringAsObject[line.split(':')[0]] = line.split(':')[1];
    }
  }
);

stringAsObject.Title = 'NewValue';
about 4 years ago · Santiago Gelvez Denunciar

0

You can use replace method like that:

string.replace("Hello World", "Test");
about 4 years ago · Santiago Gelvez 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