Alternative Regexp
var arabic = /[\u0600-\u06FF]/g,
string = 'مرحبا';
count = string.split(arabic).length - 1);
var match = string.match(arabic);
count = match ? match.length : 0;
Alternative Cycle for Performance
If performance is important, you can also do a loop:
function count(string){
var char, i, len = string.length, count = 0;
for (i = 0; i < len; ++i)
if ((char = string.charCodeAt(i)) >= 0x600 && char <= 0x6ff)
++count;
return count;
}
In some quick JSPerf tests, the loop version works 30 times better on short lines and 10 times better on long lines (7000 characters). Change between browsers.
source
share