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>');
Author by
Nicer
Updated on June 07, 2022Comments
-
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 almost 7 yearsThe
<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 almost 7 yearsHi Nikhil,I am geeting this data from client side which I cannot manipulate.
-
evolutionxbox almost 7 yearsDon'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 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 almost 7 years@Nicer angular & javascript you are using are the client side. Do you mean you can't touch the HTML ?
-
Nicer almost 7 years@Nicer exactly...
-
Nicer almost 7 yearsI mean I am getting data from a remote area which I cant touch.
-
-
alex3683 almost 7 yearsDidn't think about
outerHTML
being writeable. Good to know it is. Thanks :-) -
Hema Nandagopal almost 7 yearsOP is using Angular js.So,I think using jquery might not be an good option.
-
Hema Nandagopal almost 7 yearsOP is using Angular js.So,I think using jquery might not be an good option.