0

I have a javascript string like below:

var content = 'Robert John Testy'
content = content.replace('John','<MiddleName>');

It returns 'Robert Testy' instead of 'Robert <MiddleName> Testy'

Any idea's? Thanks.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
Josh
  • 569
  • 1
  • 11
  • 35
  • 3
    No, it returns `'Robert Testy'` - if you can't see it your likely viewing it in an HTML context where its perceived as a mangled tag and removed. console.log() it. – Alex K. Mar 26 '15 at 14:39
  • It works fine. Are you substituting with another value? – wonderbell Mar 26 '15 at 14:53

1 Answers1

1

Looks like you're running it in HTML context:

In that case you must use '&lt;MiddleName&gt; which will be displayed as <MiddleName> when rendered in HTML

var content = 'Robert John Testy'
content = content.replace('John','&lt;MiddleName&gt;');

Just demonstrating the difference between both:

 <html>
  <body>
     <div id="results1"> </div>
     <div id="results"> </div>

     <script type="text/javascript">
             var content = 'Robert John Testy'
             content = content.replace('John','&lt;MiddleName&gt;');
             document.querySelector("#results").innerHTML =content;
             content = 'Robert John Testy'
             content = content.replace('John', '<MiddleName>');
                
             document.querySelector("#results1").innerHTML =content;

     </script>
  </body>
 </html>
 
mohamedrias
  • 18,326
  • 2
  • 38
  • 47