w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Count number of Arabic and English characters in a String in JavaScript

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




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.