...

View Full Version : How to Handle Unicode Characters



sachinonnet
01-20-2009, 12:56 PM
I written below javascript function to handle Unicode characters in HTML text boxes.

code for & and ' ' goes into infinite loop, is there any better way to achive this ?

function handleSpecialCharacters(){
var text = document.getElementById('Article_Title').value;
var text1 = "";
var iChars = "<>\":[]{}`\';()@$#%&";
for (var i = 0; i < text.length; i++) {
if (iChars.indexOf(text.charAt(i)) != -1){
var str = iChars.charAt(iChars.indexOf(text.charAt(i)));
if(str == '<'){
alert("<");
text = text.replace(str,"&lt;");
}
if(str == '>'){
alert(">");
text = text.replace(str,"&gt;");
}
if(str == '&'){
alert("&");
text = text.replace(str,"&amp;");
}
if(str == ' '){
text = text.replace(str,"&nbsp;");
}
if(str == '"'){
alert("double quote");
text = text.replace(str,"&quot;");
}
if(str == '''){
text = text.replace(str,"&apos;");
}

}
}
alert("Modified Text : " +text);
}


thanks for you help

Philip M
01-20-2009, 01:58 PM
Your problem is that you are changing the value of text by placing & characters in it which are then found by the next pass of the loop, and also screwing up the character count. So you must output the results to a different variable modtext, and temporarily replace & by something else such as ~, and then at the end change all ~ to &.

Try this:-




<script type = "text/javascript">

function handleSpecialCharacters() {
var text = "The&cat>sat<on&the<mat";
var modtext = text;
var iChars = "<>\":[]{}`\';()@$#%&";

for (var i = 0; i < text.length; i++) {
if (iChars.indexOf(text.charAt(i)) != -1){
var str = iChars.charAt(iChars.indexOf(text.charAt(i)));

if(str == '&') {
modtext = modtext.replace(str,"~amp;");
}

if(str == '<') {
modtext = modtext.replace(str,"~lt;");
}

if(str == '>') {
modtext = modtext.replace(str,"~gt;");
}

if(str == ' ') {
modtext = modtext.replace(str,"~nbsp;");
}

if(str == '"') {
modtext = modtext.replace(str,"~quot;");
}

if(str == "'") {
modtext = modtext.replace(str,"~apos;");
}
}

}

modtext = modtext.replace(/\~/g, "&");
alert ("Modified Text : " + modtext);

}

</script>



Note that if(str == '''){ must be if(str == "'"){


BTW, the time to say "thanks" is afterwards, not beforehand which gives the impression that you take other people's unpaid assistance for granted. Or as British politician Neil Kinnock put it, "Don't belch before you have had the meal." Prefer to use "please" beforehand and if you find a response helpful then you can use the "Thank User For This Post" button.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum