我想在javascript中计算Unicode内容的最大字长。
答案 0 :(得分:0)
喜欢这个吗?
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'));
答案 1 :(得分:0)
var maxLength = 0;
s.replace(/\w+/g, function(g0){ maxLength = Math.max(maxLength, g0.length);});
这有点滥用,但有效。在这里,我们使用replace
的回调迭代匹配的单词(这里是字母数字和下划线,但你可以改变它),并检查每个匹配单词的长度与我们当前的最大长度。