使用javascript仅显示整个单词

时间:2011-08-09 06:07:24

标签: javascript

我有一个文字说“用于测试的示例文本”。我需要在div中只显示十个字符。 所以我在文本上做了子串

txt.substring(0,10) 

这给了我“样本t”。由于它难以显示未终止的单词,我只需要显示“A Sample”即可显示。我该怎么做?

4 个答案:

答案 0 :(得分: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"

让我知道它是否有帮助!

答案 1 :(得分:0)

如果单词长度超过十个字符,假设你的字符串比空字符串要短,那么:

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);
}

答案 2 :(得分:0)

使用substring方法执行此操作 我认为你应该使用substring方法添加一个过滤器来检查第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(' '));
}

答案 3 :(得分: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;
 }
相关问题