Click here to Skip to main content
15,895,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm currently working on my school project and am to build a forum for the project,But right now am facing this problem where i want users to be able to post their html source code as it works in this forum,but the problem is that the code runs or scatters my design when retrieve from my DB.I try using repalce() in jquery but i could only replace < with < but i want a function to be able to replace others such as >,",' and & so my question is how can i write this function.


the below code work to replace the < but when i try including >,",' and & in the function it will stop work how can i make it work please someone should help me out.


What I have tried:

function convert(div){
         var str =  $(div).html();
         var str2 =  str.replace(/</g,"&lt;");
           var sta =  $(div).html(str2);
             return sta;
            }
Posted
Updated 10-Sep-17 11:35am
v2

1 solution

Quote:
the below code work to replace the < but when i try including >,",' and & in the function it will stop work how can i make it work please someone should help me out.

I think the key is to start with replacing & first and then the other chars in any order.
JavaScript
var str2 =  str.replace(/&/g,"&amp;");
var str2 =  str2.replace(/</g,"&lt;");
var str2 =  str2.replace(/>/g,"&gt;");
...

Because all encoded chars starts with '&', you need to replace it first.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900