1

I have a JavaScript function that counts the number of characters in some text area. My function is as follows..

function limiting(obj) {
    var count = $("#counter > span");
    var txt = $(obj).val();
    var length = txt.length;
      $(cnt).html(length);
}

I call this function every time someone types in text area and it works. Now I want this function to act as:

  • Detect arabic characters
  • Add 2 to the count for each Arabic character
  • Add 1 to the count for each English character

for example if we have 2 Arabic and 3 English characters then the count should be 7, currently it is 5. I have googled it but could not find anything clear. Thanks

Sikander
  • 834
  • 2
  • 10
  • 33
  • I'm not sure if this might help: http://stackoverflow.com/questions/15453194/how-to-calculate-the-length-of-an-encoded-string – adamj Feb 14 '14 at 06:57

1 Answers1

1

Arabic characters are non-ASCII while English characters are ASCII. Now in a loop, iterating over your string, check if the character is ASCII or not.

function isASCII(str) {
return /^[\x00-\x7F]*$/.test(str);
}

if true add 1 to the count if false add 2.

 function countWeight(string){
  var count = 0;
   for (var i = 0; i<string.length; i++){
     if (isASCII(string.charAt(i)))
      count+=1;
     else
      count+=2;
   }
  return count;
 }

You can do this simply in this way

 function limiting(obj) {
  var cnt= $("#counter > span");
  var txt = $(obj).val();
  var count = 0;
  for (var i = 0; i< txt.length; i++)
   count += /^[\x00-\x7F]*$/.test(txt.charAt(i))?1:2;
  $(cnt).html(count);
 }

TEST

countWeight("asdبي");//returns 7
ahmadalibaloch
  • 5,851
  • 2
  • 50
  • 59