0

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.

piet.t
  • 11,718
  • 21
  • 43
  • 52
AA Shakil
  • 538
  • 4
  • 14

1 Answers1

1

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>
Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
  • What is LT_LT and GT_GT here? Are they the other way of < and > – AA Shakil Jan 21 '18 at 07:14
  • 1
    naah !!! those are used as temporary replacement. You may use something which is unlikely to be a syntax or word. You need to use something in place of < and > temporarily. When you apply the first replacement you again get some < in so that > sign is again going to be replaced by your initial replacement. That is why your were having false result. So you need to use some thing LT_LT GT_GT are temporary thing – Mustofa Rizwan Jan 21 '18 at 07:17
  • 1
    Ow I have got it. Thanks for this awesome idea. – AA Shakil Jan 21 '18 at 07:24