开发者

Calculate the biggest word size in bytes of submitted content

I want to calculate the开发者_如何学JAVA largest word size in byte for Unicode content in javascript.


var maxLength = 0;
s.replace(/\w+/g, function(g0){ maxLength = Math.max(maxLength, g0.length);});

This is slightly abusive, but effective. Here, we're using the callback of replace to iterate over the matched words (here, alphanumeric and underscores, but you can change that), and check the length of every matched word against our current maximal length.


Like this?

function largestWord(str) {
  var words = encodeURIComponent(str).replace(/[^a-zA-Z0-9\%]/," ").split("%20"); // we cannot remove the dots since \W kills all foreign chars too
  alert(words);
  var longest = "";
  for (var i=0, n=words.length;i<n;i++) {
    var test = words[i].replace("%2C",""); // we need to get rid of dots and other punktuation here
    alert(test +':'+longest)
    if (test.length > longest.length) longest=test;
  }
  return decodeURIComponent(longest)  
}

document.write(largestWord('Duh disti dusti du dist du Børk, Bårker, Bærkest'));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜