使用javascript仅显示整个单词

使用javascript仅显示整个单词,javascript,Javascript,我有一个文本,上面写着“测试用样本文本”。我只需要在一个div中显示十个字符。 所以我在文本上做子串 txt.substring(0,10) 这给了我一个“样本t”。因为显示一个未终止的单词很难看,所以我只需要显示要显示的“示例”。我该怎么做?你可以做你该做的,将文本替换为10个字符 然后使用txt.lastIndexOf(“”)查找文本中的最后一个空格 然后使用它再次对文本进行子串 例如: var txt = "A Sample Text"; txt = txt.subString(0,1

我有一个文本,上面写着“测试用样本文本”。我只需要在一个div中显示十个字符。 所以我在文本上做子串

txt.substring(0,10) 

这给了我一个“样本t”。因为显示一个未终止的单词很难看,所以我只需要显示要显示的“示例”。我该怎么做?

你可以做你该做的,将文本替换为10个字符

然后使用txt.lastIndexOf(“”)查找文本中的最后一个空格

然后使用它再次对文本进行子串

例如:

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

如果有帮助,请告诉我

假设如果单词长度超过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);
}
函数缩短(txt)
{
//如果短或前10个字符后出现空格,则保留子字符串(简单大小写)

如果(txt.length使用子字符串方法执行此操作 我认为您应该添加一个过滤器,用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(' '));
}

你想让所有的单词都大写吗?你想如何显示“Stackoverflow”(超过十个字符)?@Thilo我总是在一个句子中使用这个词,而不是在一个单词上。所以这不会是一个问题。是的,但是如果它将被用在任何更大规模的场合,它可能不会是一个问题。
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;
 }