截斷文字
重要性:5
建立一個函式 truncate(str, maxlength)
,檢查 str
的長度,如果超過 maxlength
,就用省略號字元 "…"
取代 str
的結尾,讓它的長度等於 maxlength
。
這個函式的結果應該是截斷(如果需要)後的字串。
例如
truncate("What I'd like to tell on this topic is:", 20) == "What I'd like to te…"
truncate("Hi everyone!", 20) == "Hi everyone!"
最大長度必須是 maxlength
,所以我們需要把它剪得更短一點,才能為省略號騰出空間。
請注意,省略號實際上只有一個 Unicode 字元。那不是三個點。
function truncate(str, maxlength) {
return (str.length > maxlength) ?
str.slice(0, maxlength - 1) + '…' : str;
}