How to replace a html tag in js?

19,024

Solution 1

If you want to stick with your simple string manipulation, you need to use regular expressions and correct the replacements in your replace calls:

text = text.replace(/<font[^>]*>/g,'<p>').replace(/<\/font>/g,'</p>');

Solution 2

block.outerHTML = "<p>" + block.innerHTML + "</p>" 

where block is any HTML block it just left to select it correctly with:

var block = document.querySelector(".selector");

Solution 3

Since you just need to replace the string you can do this with just one replace statement.

text = text.replace(/<(\/*)font[^>]*>/g, '<$1p>');
Share:
19,024
Nicer
Author by

Nicer

Updated on June 07, 2022

Comments

  • Nicer
    Nicer almost 2 years

    I have a string in which there are continous occurances of a font tag

     <font color="blue">DATA ENTRY</font> 
    

    and in some cases like this

     <font class="beat">DATA ENTRY</font> 
    

    I want to replace the 2 tags with

    So that it looks like this

         <p>DATA ENTRY</p>
    

    I tried this ,can anyone please suggest me help.Thanks.

     text = text.replace('<font [^"]*>',<p>).replace('</font>','');
    
    • Nikhil Nanjappa
      Nikhil Nanjappa almost 7 years
      The <font> is a deprecated tag. Is there a reason why you need to use it? You could instead use the same <p> tag and just remove the class later.
    • Nicer
      Nicer almost 7 years
      Hi Nikhil,I am geeting this data from client side which I cannot manipulate.
    • evolutionxbox
      evolutionxbox almost 7 years
      Don't use regex with HTML. Instead convert it to a temporary DOM Element, manipulate it, and then convert back to text if needed.
    • Koushik Chatterjee
      Koushik Chatterjee almost 7 years
      @Nicer getting this data from client side means? you have to convert in server side (javascript in nodejs) or client side (javascript in browser)?
    • Nikhil Nanjappa
      Nikhil Nanjappa almost 7 years
      @Nicer angular & javascript you are using are the client side. Do you mean you can't touch the HTML ?
    • Nicer
      Nicer almost 7 years
      @Nicer exactly...
    • Nicer
      Nicer almost 7 years
      I mean I am getting data from a remote area which I cant touch.
  • alex3683
    alex3683 almost 7 years
    Didn't think about outerHTML being writeable. Good to know it is. Thanks :-)
  • Hema Nandagopal
    Hema Nandagopal almost 7 years
    OP is using Angular js.So,I think using jquery might not be an good option.
  • Hema Nandagopal
    Hema Nandagopal almost 7 years
    OP is using Angular js.So,I think using jquery might not be an good option.