Forum Moderators: open

Message Too Old, No Replies

encoding text to HTML special charictors

         

mehh

3:18 pm on Dec 30, 2006 (gmt 0)

10+ Year Member



i need a function that will turn text into special charictors eg "<" goes in "<lt;" comes out and i was wondering if this function is built in to Javascript like it is in php, or do i have to make it myself?

eelixduppy

2:49 am on Dec 31, 2006 (gmt 0)



Seems like one doesn't exist. Try a search [google.com].

Best of luck!

disgracian

7:52 am on Jan 1, 2007 (gmt 0)

10+ Year Member



[pre]function special(xStr){
var lt=/</g;
var gt=/>/g;
xStr=xStr.replace(lt,"&lt;");
xStr=xStr.replace(gt,"&gt;");
return xStr;
}[/pre]

That's just a primitive example I knocked up that will convert all opening and closing pointy-brackets in a string given to that function. There is no doubt a more efficient and scalable way to write this, but it embodies the basic principle.

Cheers,
D.

disgracian

8:20 am on Jan 1, 2007 (gmt 0)

10+ Year Member



After giving it a bit of thought, I modified the function to this:

[pre]function special(xStr){
var entArray=new Object();
entArray["&lt;"]=/</g;
entArray["&gt;"]=/>/g;
for(x in entArray)xStr=xStr.replace(entArray[x],x);
return xStr;
}[/pre]

Just keep adding to the associative array for each character you want to replace.

Cheers,
D.

mehh

2:04 pm on Jan 1, 2007 (gmt 0)

10+ Year Member



thanks disgracian your function looks very simmilar to the one I made myself:
function txt2html(l, prev)
{
var htmlarr=new Array();
htmlarr["\n"]="<br />"
htmlarr["<"] ="&lt;"
htmlarr[">"] ="&gt;"
htmlarr["&"] ="&amp;"
htmlarr["\""]="&#34;"
htmlarr["\'"]="&#39;"
htmlarr[" "]="&nbsp;"
for (var i in htmlarr)
{
if(l==i){ if(i!=" "¦¦prev==" "){ l=htmlarr[i];}}
}
return l;
}

penders

5:29 pm on Jan 1, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hi mehh, I realise your function is probably tailored to your needs, but I was just wondering whether you intentionally want to convert all spaces (" ") to non-breaking-spaces (&nbsp;)? Hhhhmm, maybe you aren't?