bpat
bpat

Reputation: 77

Regex string replace, while keeping the original newlines

I have a multi string:

My input:

var str = `The left lower lung thick parenchymal band as seen on prior 
           scan remains not hypermetabolic.The posterior left lung base tiny
           density as seen on prior scan remains not significantly 
           hypermetabolic.`;
var element = 'The left lower lung thick parenchymal band as seen on prior scan remains not hypermetabolic';
var newElement = '<p1>The left lower lung thick parenchymal band as seen on prior scan remains not hypermetabolic</p1>';

How can I replace element with newElement in my original str using a regex?

My attempt:

str.replace(/[^\\S ]/, ' ').replace(element, newElement) 

When I try to replace using regex, I am not able to ignore the newlines and replace them at the same time.

Expected Result:

var str = `<p1>The left lower lung thick parenchymal band as seen on prior
            scan remains not hypermetabolic</p1>.The posterior left lung base tiny  
            density as seen on prior scan remains not significantly
            hypermetabolic.`;

Upvotes: 0

Views: 75

Answers (1)

trincot
trincot

Reputation: 350137

You can create a regular expression dynamically by changing the spacing in the element string with \s+: that will match newlines also:

var str = `:
    The left lower lung thick parenchymal
    band as seen on prior scan remains not hypermetabolic.  The posterior left 
   lung base tiny  density as seen on prior scan remains not significantly 
   hypermetabolic.
 `;

var element = 'The left lower lung thick parenchymal band as seen on prior scan remains not hypermetabolic';
var newElement = '<p1>The left lower lung thick parenchymal band as seen on prior scan remains not hypermetabolic<p1>';

let regex = RegExp(element.replace(/ +/g, "\\s+"), "g");
str = str.replace(regex, newElement);

console.log(str);

If you want the replacement to also retain the original newlines (assuming you only want to wrap within two <p1>), then use the $& backreference in newElement:

var str = `:
    The left lower lung thick parenchymal
    band as seen on prior scan remains not hypermetabolic.  The posterior left 
   lung base tiny  density as seen on prior scan remains not significantly 
   hypermetabolic.
 `;

var element = 'The left lower lung thick parenchymal band as seen on prior scan remains not hypermetabolic';
var newElement = '<p1>$&<p1>';

let regex = RegExp(element.replace(/ +/g, "\\s+"), "g");
str = str.replace(regex, newElement);

console.log(str);

Remark:

It is not clear what <p1> stands for. If this is supposed to be an XML tag, then realise that the closing tag should be </p1> with the forward slash.

If your element string has characters that have a special meaning in regexes then make sure to escape them. See this Q&A on how to do that.

Upvotes: 2

Related Questions