缩短字符串而不在JavaScript中剪切单词

Jos*_*edo 87 javascript string substring

我在JavaScript中对字符串操作不太熟悉,我想知道如何在不删除任何字的情况下缩短字符串.我知道如何使用substring,但不知道indexOf或其他任何东西.

说我有以下字符串:

text = "this is a long string I cant display"
Run Code Online (Sandbox Code Playgroud)

我想将其减少到10个字符,但如果它不以空格结束,请完成单词.我不希望字符串变量看起来像这样:

"这是一个很长的字符串,我不能说"

我想让它完成这个词直到空格出现.

NT3*_*3RP 168

如果我理解正确,你想将一个字符串缩短到一定长度(例如缩短"The quick brown fox jumps over the lazy dog"到6个字符而不切断任何单词).

如果是这种情况,您可以尝试以下内容:

var yourString = "The quick brown fox jumps over the lazy dog"; //replace with your string.
var maxLength = 6 // maximum number of characters to extract

//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);

//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
Run Code Online (Sandbox Code Playgroud)

  • @josh绝对不是".replace"在"jQuery函数"中不起作用.甚至没有"jQuery函数"这样的东西. (9认同)
  • 如果在比maxLength短的字符串上使用它,则最后一个字会被切断.也许@AndrewJuniorHoward已经说明了这个问题(`maxLength + 1`),但我通过简单地添加这行来修复它:`var yourString + ="";` (4认同)
  • 不应该是"maxLength + 1".如果maxLength大于或等于完整句子长度,则不包括最后一个单词.但感谢您的解决方案. (3认同)
  • 不幸的是,如果你带走"狐狸跳过懒狗"部分,结果将是"快速棕色",当它应该是"快速棕色狐狸". (3认同)
  • 这总是削减了最后一个字. (2认同)

Ham*_*ish 89

有很多方法可以做到这一点,但正则表达式是一个有用的单行方法:

"this is a longish string of text".replace(/^(.{11}[^\s]*).*/, "$1"); 
//"this is a longish"
Run Code Online (Sandbox Code Playgroud)

此表达式返回前11个(任意)字符以及任何后续非空格字符.

示例脚本:

<pre>
<script>
var t = "this is a longish string of text";

document.write("1:   " + t.replace(/^(.{1}[^\s]*).*/, "$1") + "\n");
document.write("2:   " + t.replace(/^(.{2}[^\s]*).*/, "$1") + "\n");
document.write("5:   " + t.replace(/^(.{5}[^\s]*).*/, "$1") + "\n");
document.write("11:  " + t.replace(/^(.{11}[^\s]*).*/, "$1") + "\n");
document.write("20:  " + t.replace(/^(.{20}[^\s]*).*/, "$1") + "\n");
document.write("100: " + t.replace(/^(.{100}[^\s]*).*/, "$1") + "\n");
</script>
Run Code Online (Sandbox Code Playgroud)

输出:

1:   this
2:   this
5:   this is
11:  this is a longish
20:  this is a longish string
100: this is a longish string of text
Run Code Online (Sandbox Code Playgroud)

  • @josh你应该能够通过使用正则表达式对象使最大长度变量:`t.replace(new RegExp("^(.{"+ length +"} [^\s]*).*"),"$ 1 ")` (2认同)

Chr*_*lli 51

令我感到惊讶的是,对于像这样的简单问题,有很多难以阅读的答案,有些答案,包括所选答案,都不起作用.

我通常希望结果字符串最多为 maxLen字符.我也使用相同的功能来缩短URL中的slu ..

str.lastIndexOf(searchValue[, fromIndex]) 采用第二个参数,该参数是在字符串中向后搜索的索引,使得事情变得高效和简单.

// Shorten a string to less than maxLen characters without truncating words.
function shorten(str, maxLen, separator = ' ') {
  if (str.length <= maxLen) return str;
  return str.substr(0, str.lastIndexOf(separator, maxLen));
}
Run Code Online (Sandbox Code Playgroud)

这是一个示例输出:

for (var i = 0; i < 50; i += 3) 
  console.log(i, shorten("The quick brown fox jumps over the lazy dog", i));

 0 ""
 3 "The"
 6 "The"
 9 "The quick"
12 "The quick"
15 "The quick brown"
18 "The quick brown"
21 "The quick brown fox"
24 "The quick brown fox"
27 "The quick brown fox jumps"
30 "The quick brown fox jumps over"
33 "The quick brown fox jumps over"
36 "The quick brown fox jumps over the"
39 "The quick brown fox jumps over the lazy"
42 "The quick brown fox jumps over the lazy"
45 "The quick brown fox jumps over the lazy dog"
48 "The quick brown fox jumps over the lazy dog"
Run Code Online (Sandbox Code Playgroud)

对于slu ::

for (var i = 0; i < 50; i += 10) 
  console.log(i, shorten("the-quick-brown-fox-jumps-over-the-lazy-dog", i, '-'));

 0 ""
10 "the-quick"
20 "the-quick-brown-fox"
30 "the-quick-brown-fox-jumps-over"
40 "the-quick-brown-fox-jumps-over-the-lazy"
Run Code Online (Sandbox Code Playgroud)

  • 如果由于某种原因`str`是'undefined`,这会崩溃.我添加了`if(!str || str.length <= maxLen)return str;` (2认同)
  • @shrewquest 它有效。如果分隔符不在字符串中,则如果“str.length &lt;= maxLen”,则返回字符串本身。否则它返回一个空字符串。 (2认同)

ken*_*bec 18

每个人似乎都忘记了indexOf有两个参数 - 要匹配的字符串,以及从中开始查找的字符索引.您可以在10个字符后的第一个空格处断开字符串.

function cutString(s, n){
    var cut= s.indexOf(' ', n);
    if(cut== -1) return s;
    return s.substring(0, cut)
}
var s= "this is a long string i cant display";
cutString(s, 10)

/*  returned value: (String)
this is a long
*/
Run Code Online (Sandbox Code Playgroud)


Leo*_* Li 11

Lodash具有专门为此编写的功能: _.truncate

const truncate = _.truncate
const str = 'The quick brown fox jumps over the lazy dog'

truncate(str, {
  length: 30, // maximum 30 characters
  separator: /,?\.* +/ // separate by spaces, including preceding commas and periods
})

// 'The quick brown fox jumps...'
Run Code Online (Sandbox Code Playgroud)


Joa*_*ger 11

这是一行的解决方案。

text = "this is a long string I cant display"

function shorten(text,max) {
    return text && text.length > max ? text.slice(0,max).split(' ').slice(0, -1).join(' ') : text
}


console.log(shorten(text,10));
Run Code Online (Sandbox Code Playgroud)


Seb*_*ber 7

基于NT3RP的答案,它没有处理一些极端情况,我已经制作了这段代码.它保证不返回大小> maxLength事件的文本,...最后添加省略号.

这也处理一些角落案例,例如一个单词为> maxLength的文本

shorten: function(text,maxLength,options) {
    if ( text.length <= maxLength ) {
        return text;
    }
    if ( !options ) options = {};
    var defaultOptions = {
        // By default we add an ellipsis at the end
        suffix: true,
        suffixString: " ...",
        // By default we preserve word boundaries
        preserveWordBoundaries: true,
        wordSeparator: " "
    };
    $.extend(options, defaultOptions);
    // Compute suffix to use (eventually add an ellipsis)
    var suffix = "";
    if ( text.length > maxLength && options.suffix) {
        suffix = options.suffixString;
    }

    // Compute the index at which we have to cut the text
    var maxTextLength = maxLength - suffix.length;
    var cutIndex;
    if ( options.preserveWordBoundaries ) {
        // We use +1 because the extra char is either a space or will be cut anyway
        // This permits to avoid removing an extra word when there's a space at the maxTextLength index
        var lastWordSeparatorIndex = text.lastIndexOf(options.wordSeparator, maxTextLength+1);
        // We include 0 because if have a "very long first word" (size > maxLength), we still don't want to cut it
        // But just display "...". But in this case the user should probably use preserveWordBoundaries:false...
        cutIndex = lastWordSeparatorIndex > 0 ? lastWordSeparatorIndex : maxTextLength;
    } else {
        cutIndex = maxTextLength;
    }

    var newText = text.substr(0,cutIndex);
    return newText + suffix;
}
Run Code Online (Sandbox Code Playgroud)

我想你可以轻松删除jquery依赖,如果这困扰你.

  • 我喜欢这个解决方案,但不应该传递给`$ .extend`的args被反转? (3认同)

Mic*_*umo 5

我迟到了,但这是我想出的一个小而简单的解决方案来返回大量单词。

它与您对characters的要求没有直接关系,但它提供的结果与我相信您所追求的结果相同。

function truncateWords(sentence, amount, tail) {
  const words = sentence.split(' ');

  if (amount >= words.length) {
    return sentence;
  }

  const truncated = words.slice(0, amount);
  return `${truncated.join(' ')}${tail}`;
}

const sentence = 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.';

console.log(truncateWords(sentence, 10, '...'));
Run Code Online (Sandbox Code Playgroud)

请参阅此处的工作示例:https : //jsfiddle.net/bx7rojgL/