I just found the folloing script that limt the chars in a textarea field. As I am working with UNICODE ( I work in Brasil and our language is portugues whith a several special chars), I woukd like to do the same as the script but changing the limit to bytes. I am a javascript begginer, and found an other script that count the bytes in a string, but I didi not know how to implement it in the first script to limit it to yhe byte count,
Thanks in advance for any help.
Here are the scrips:
1 - Chars limit:
Code:
<script language="javascript" type="text/javascript">
<!--
function max1(txarea){
total = 50;
tam = txarea.value.length;
str="";
str=str+tam;
Digitado1.innerHTML = str;
Restante1.innerHTML = total - str;
if (tam > total){
aux = txarea.value;
txarea.value = aux.substring(0,total);
Digitado1.innerHTML = total
Restante1.innerHTML = 0
}
<script language="javascript" type="text/javascript">
// contar bytes
function charCount(str) {
// counts the number of unicode characters, which may differ from str.length
var esc = escape(str); // escape more robust than encodeURI
return esc.replace(/%uD[C-F]../g,'')
.replace(/%u..../g,'"')
.replace(/%../g,"'")
.length;
}
function SevenBitsOrLess(str) {
// returns false if str includes a unicode character requiring 8 or more bits
var esc = escape(str);
if (esc.match(/%u/)) return false;
return (!esc.match(/%[89A-F]/));
}
// Example
//var str0 = "ab$1_^%25$.%D8%B7 %EA%96%A4,%F3%87%BB%81";
//str = decodeURI (str0);
//alert (charCount(str));
/*
Note that in the example,
str0.length => 40
str.length => 15
alert (charCount(str)) => 14
*/
</script>
01-11-2010, 08:49 AM
Kor
As far as I know, the number of characters in javascript (the length property of a text field or a textarea) has nothing to do with the bytes/character nor with the unicode.
What do you need? A code which will count and limit the number of characters in a textarea? Or a bytes counter?
01-11-2010, 10:32 AM
odaier
Hi Kor,
Thank you for your reply.
As you can see at the script #2, it counts the bytes lengt. So, in Portuguese, the string "aviação" ("aviação") has 7 characteres length and 9 bytes length. If I use the script # 1 I can limt the character lenght, that may be different of the bytes lenght
Sory about my english.