How to calculate the length of an encoded string?

喜夏-厌秋 提交于 2019-12-13 17:41:03

问题


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)


回答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.




回答2:


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/



来源:https://stackoverflow.com/questions/15453194/how-to-calculate-the-length-of-an-encoded-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!