Replace all words between two words by some text

I have the following code. I would like to replace all occurrences of ~23 between the starting word <pre> and ending word </pre> by the word 63. I tried the below code, but it does no replacement. I should be getting the following string after replacement :
<div>dds ~23 ssd</div><pre>sdddsds 63 mike</pre>

const str = "<div>dds ~23 ssd</div><pre>sdddsds ~23 mike</pre>";
str = str.replaceAll(/(<pre>)*(~23)(?=(\<\/pre>))/g,"63");

Not an expert here but this may be a possibility:

let str = "<div>dds ~23 ssd</div><pre>sdddsds ~23 mike</pre>";
str = str.replaceAll(/(?=(<pre>).*)(~23)(?=(.*\<\/pre>))/g,"63");

What is the main change compared to the original regex? Just that spaces and other caracters bw the tags will still match, and they won’t be part of the replaced text because it’s within a lookahead.

I tried your code, but it doesn’t work. You can see your code being used at this link: Code Demo of your sample code

1 Like

My bad, this should

/(?<=(<pre>.*))~23(?=(.*<\/pre>))/

Or complete:

let str = "<div>dds ~23 ssd</div><pre>sdddsds ~23 mike</pre>";
str = str.replaceAll(/(?<=(<pre>.*))~23(?=(.*<\/pre>))/g,"63");
  • ?<= is a look behind.
1 Like

Yes that one works. Thankyou for your prompt help.
I tested it at Code sample

You may try the following ones as well:

let str = "<div>dds ~23 ssd</div><pre>sdddsds ~23 mike</pre>";
str = str.replaceAll(/~23(?<=(<pre>.*))(?=(.*<\/pre>))/g,"63");

and

let str = "<div>dds ~23 ssd</div><pre>sdddsds ~23 mike</pre>";
str = str.replaceAll(/(?<=(<pre>.*))(?=(.*<\/pre>))~23/g,"63");

i.e look arounds can be placed anywhere (or so it seems, but that’s my conclusion after trying.)

1 Like

The first code sample works. Code Sample 1
The second code sample also works. Code Sample 2

I will need to study the three regex that you have provided and understand them. I appreciate your help.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.