2010-08-12 32 views
0

我想計算javascript中Unicode內容的最大字節數。計算提交內容的字節數的最大單詞大小

+1

你是什麼意思的單詞?大概在語法上呢?是最新的三個詞還是一個? – 2010-08-12 09:06:21

+0

句子中的單個單詞。例如, '你好,這很好。'這裏'你好','這個','是'和'好'是單獨的詞。 – user248092 2010-08-12 09:10:52

+0

* Unicode *部分有多重要?你真的需要所有的角色,還是隻能處理幾個歐洲的角色? – Kobi 2010-08-12 14:21:34

回答

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')); 
+0

或返回longest.length或返回decodeURIComponent(最長).length – mplungjan 2010-08-12 09:19:46

+0

上述函數不適用於字符串。 – user248092 2010-08-12 12:53:04

+0

現在好點了嗎?請注意,該功能仍需要處理其他punktuation – mplungjan 2010-08-12 13:35:52

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

這是稍微辱罵,但有效。在這裏,我們使用replace的回調來遍歷匹配的單詞(這裏是字母數字和下劃線,但您可以更改它),然後根據當前最大長度檢查每個匹配單詞的長度。

+0

好主意,但嘗試在 var str =「Duh disti dusti du dist duBørk,Bårker,Bærkest」; – mplungjan 2010-08-12 13:35:21

+0

@mplungjan - 它失敗了,但你只需要改變'\ w'來使它工作。 JavaScript不支持unicode。如果你想要完整的Unicode支持,你最好的選擇可能是一個庫,如http://xregexp.com/plugins/。使用'encodeURIComponent'是一個聰明的黑客攻擊,但它也會在所有特殊字符上失敗(嘗試使用'@'或其他任何unicode非字母字符) - 不幸的是,如果你想獲得真正的支持, :)' – Kobi 2010-08-12 14:15:33