AA Shakil
AA Shakil

Reputation: 556

RegExp replacing is causing false result while replacing again

My String : "<p>Stacked" I want to replace it to "<font color=' blue'><</font>p<font color='blue'>></font>Stacked

So I have used this : ⬇

var rox = /([<])([a-z1-9]+)([>])/;


function testInfo(phoneInput){ 
    var startTag = "<font color='blue'>";
    var endTag = "</font>";
    var OK = phoneInput.value.replace(rox, function(x){
        var lt = x.replace(/([<])/, startTag+'&lt;'+endTag);
        var gt = lt.replace(/([>])/ , startTag+'&gt;'+endTag);
        return gt;
    });

It returns like this

<font color='blue'<font color='blue'>p<font color='blue'>&gt;</font>

It means when I am replacing the

Stack First time it is replacing to

 **<font color='blue'>&lt;</font>p<font color='blue'>&gt;</font>** But next time it is replacing the **">"** of the *font tag*. Lot *">"* of **p tag**.

Problem


How can I fix it? I am trying something to color/highlight code.

Upvotes: 0

Views: 119

Answers (1)

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

You may try this:

str = `<p>Stacked`;
const subst1 = `LT_LTfont color=' blue'GT_GT&lt;`;
const subst2 = `LT_LTfont color=' blue'GT_GT&gt;`;
str = str.replace(/</g, subst1);
str = str.replace(/>/g, subst2);

str = str.replace(/GT_GT/g,`>`);
str = str.replace(/LT_LT/g,`<`);

$("#kk").html(str);
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="kk">

</div>

Upvotes: 1

Related Questions