1

so i have an arabic string then i encode it using encodeURIComponent, then i try to know the length from the encoded string but this code don't work why? http://jsfiddle.net/mCwaj/

var str="قال على";
var encd=encodeURIComponent(str);
alert(encd);
alert(custom_length(encd));
function custom_length(str){
var tab=str.match(/%../g);
return tab.length;
}

the result should be 7 but function returns 13, what i know is that an arabic encoded alphabet is composed like %(letter|number)(letter|number)

  • 2
    Open your browser's developer console. This is the first step in debugging. – the system Mar 16 '13 at 18:46
  • what console, i don't know how to open the console ? –  Mar 16 '13 at 18:48
  • [`Ctlr` + `Shift` + `I`](http://stackoverflow.com/questions/66420/how-do-you-launch-the-javascript-debugger-in-google-chrome), see also http://stackoverflow.com/q/988363/1048572 – Bergi Mar 16 '13 at 18:49
  • 1
    Almost all browsers have built-in developer tools. They are an indispensable tool for debugging code. I think some browsers will open them with `f12`, but look through your menus or preferences to find them. – the system Mar 16 '13 at 18:49

2 Answers2

1

You are passing the non-encoded str to your function instead of encd. Therefore, the regex does not match and the result null throws an exception on accessing its length property.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • thanks bergi but that was a typo in the code, the real problem is that the real string length is 7 and the result is 13 –  Mar 16 '13 at 18:57
  • 1
    Um, no? `%D9%82%D8%A7%D9%84%20%D8%B9%D9%84%D9%89` has 13 escape sequences, and that's what your `custom_length` counts. If you want 7, you should try `decodeURIComponent(str).length` – Bergi Mar 16 '13 at 18:59
  • 1
    If you want the string length of 7, why not (str.length)? That gives 7 – Aaron Blenkush Mar 16 '13 at 19:04
0

try using "escape()" instead of "encodeURIComponent()"

//14 charachters
var str="مرحبا أنا ياسر";  

var result=custom_length(escape(str));

alert(result); //it'll display 14

function custom_length(str){
   var tab=str.match(/%../g);
   return tab.length;
}

Demo:http://jsfiddle.net/ysinjab/KDyhp/

Yasser Sinjab
  • 578
  • 6
  • 19