-4

I need to replace all <b> and </b>tags to "" only inside <pre>tag.

I have:

<html>
...
<pre>
<b>println("I need your help");</b>
<b>println("because Iam newbie");</b>
</pre>
<pre>
<b>println("I know");</b>
<b>println("you can help me");</b>
</pre>
<b>bold stay here</b>
....
</html>

I want:

<html>
....
<pre>
println("I need your help");
println("because Iam newbie");
</pre>
<pre>
println("I know");
println("you can help me");
</pre>
<b>bold stay here</b>
....
</html>

How can I do it with replaceAll()?

drivetrdr
  • 19
  • 2

1 Answers1

-1

This is a tricky, because you can't collect more than one item in a group and at the same time repeat the group (https://www.regular-expressions.info/captureall.html). To get around this, I change the way the parser looks at it by using "lookaround" modifiiers (https://www.regular-expressions.info/lookaround.html).

var text = `<html>
<pre>
<b>println("I need your help");</b>
<b>println("because Iam newbie");</b>
</pre>
<pre>
<b>println("I know");</b>
<b>println("you can help me");</b>
</pre>
<b>bold stay here</b>
</html>`;

var re = /((<b>)([\s\S]*?)(<\/b)>)(?<=(<pre>[\s\S]*?))(?=([\s\S]*?<\/pre>))/gm;

var mod = text.replace(re,function() {
    // "arguments" is an array of all arguments 
    // passed (regardless of the function signature)
    console.log(arguments);
    return arguments[3];
});
console.log(text);
console.log(mod);
alwayslearning
  • 268
  • 2
  • 9
  • why downvote? Because I can't predict that this question has been asked before? I can understand downvoting the question, but the answer, which BTW, works perfectly? Ridiculous. – alwayslearning Apr 01 '19 at 22:31