2011-08-09 53 views
1

我有一段文字說「用於測試的示例文本」。我需要在div中只顯示十個字符。 所以我的文字僅顯示使用javascript的整個單詞

txt.substring(0,10) 

串這給了我「A樣本t」。由於它難以顯示未終止的單詞,我只需要顯示「A Sample」即可顯示。我該怎麼做呢?

+1

你想要的所有單詞大寫?你想如何顯示「Stackoverflow」(有超過十個字符)? – Thilo

+0

@Thilo我總是在句子上使用它,而不是單個單詞。所以這不會是一個問題.. – DDK

回答

2

你可以做你所做的事情,將文本串分成10個字符。

然後使用txt.lastIndexOf('')查找文本中的最後一個空格。

然後,您使用它來再次對文本進行子字符串。

例子:

var txt = "A Sample Text"; 
txt = txt.subString(0,10); // "A Sample T" 
txt = txt.subString(0, txt.lastIndexOf(' ')); // "A Sample" 

讓我知道這是否有助於!

+0

不會像「Stackoverflow」 – Thilo

+0

這樣的字太好了,但是如果它將用於任何類型的大規模,它可能不會是一個問題。 –

+0

謝謝安德烈亞斯..它像天使一樣工作:) – DDK

0

假設你寧願比爲空字符串的切斷字符串,如果字是1-10個字符長:

function shorten(txt) 
{ 
    // if it's short or a space appears after the first 10 characters, keep the substring (simple case) 
    if (txt.length <= 10 || txt[10] === ' ') return txt; 
    // get the index of the last space 
    var i = txt.substring(0, 11).lastIndexOf(' '); 
    // if a space is found, return the whole words at the start of the string; 
    // otherwise return just the first 10 characters 
    return txt.substring(0, i === -1 ? 11 : i); 
} 
0

使用子的方法來做到這一點 我想你應該添加過濾器用子串方法檢查第11個字符是否爲空格。否則最後一個有效的詞也可能被刪除。例如,獲取「用於測試的新示例文本」。

這是代碼。

str = "A sample text for testing" 
ch11_space = (str[10] == ' ') ? 0 : 1; 
str = str.substring(0,10); 
if (ch11_space) { 
    str = str.substring(0,str.lastIndexOf(' ')); 
} 
0
function getShortenedString(str) 
{ 
    var maxLength = 10; // whatever the max string can be 
    var strLength = str.length; 
    var shortenedStr = str.substr(0, maxLength); 
    var shortenedStrLength = shortenedStr.length; 
    var lastSpace = str.lastIndexOf(" "); 

    if(shortenedStrLength != strLength) 
    { 
     // only need to do manipulation if we have a shortened name 
     var strDiff = strLength - shortenedStrLength; 
     var lastSpaceDiff = shortenedStrLength - lastSpace; 

     if(strDiff > lastSpaceDiff) // non-whole word after space 
     { 
      shortenedStr = str.substr(0, lastSpace); 
     } 

    } 

    return shortenedStr; 
} 
相關問題