Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const replace = string.match(new RegExp("Title:" + "(.*)" + "Authors:")).replace("Test")

>Solution :

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:).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading