Sikander
Sikander

Reputation: 862

Count number of Arabic and English characters in a String in JavaScript

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:

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

Upvotes: 1

Views: 2371

Answers (1)

ahmadalibaloch
ahmadalibaloch

Reputation: 6021

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

Upvotes: 1

Related Questions