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

时间:2023-02-05 21:36:40

I'm not very good with string manipulation in JavaScript, and I was wondering how you would go about shortening a string without cutting any word off. I know how to use substring, but not indexOf or anything really well.

我不太擅长JavaScript中的字符串操作,我想知道如何在不删除任何单词的情况下缩短一个字符串。

Say I had the following string:

假设我有以下字符串:

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

I want to trim it down to 10 characters, but if it doesn't end with a space, finish the word. I don't want the string variable to look like this:

我想把它缩减到10个字符,但是如果没有空格结束,就把单词写完。我不希望字符串变量是这样的:

"this is a long string I cant dis"

"这是一根长长的绳子,我说不出来"

I want it to finish the word until a space occurs.

我想让它结束这个词直到一个空格出现。

13 个解决方案

#1


120  

If I understand correctly, you want to shorten a string to a certain length (e.g. shorten "The quick brown fox jumps over the lazy dog" to, say, 6 characters without cutting off any word).

如果我理解正确的话,你想要把一根绳子缩短到一定的长度(例如,把“快速棕色狐狸跳过懒狗”缩短为6个字符而不剪掉任何单词)。

If this is the case, you can try something like the following:

如果是这样的话,你可以试试以下方法:

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(" ")))

#2


68  

There are lots of ways to do it, but a regular expression is a useful one line method:

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

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

This expressions returns the first 11 (any) characters plus any subsequent non-space characters.

这个表达式返回前11个(任意)字符加上任何后续的非空格字符。

Example script:

示例脚本:

<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>

Output:

输出:

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

#3


21  

I am kind of surprised that for a simple problem like this there are so many answers that are difficult to read and some, including the chosen one, do not work .

对于这样一个简单的问题,有这么多难以阅读的答案,而有些答案,包括所选的答案,却不管用,我有点惊讶。

I usually want the result string to be at most maxLen characters. I also use this same function to shorten the slugs in URLs.

我通常希望结果字符串最多为maxLen字符。我还使用这个函数来缩短url中的slugs。

str.lastIndexOf(searchValue[, fromIndex]) takes a second parameter that is the index at which to start searching backwards in the string making things efficient and simple.

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

This is a sample output:

这是一个输出示例:

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"

And for the slug:

和鼻涕虫:

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"

#4


17  

Everyone seems to forget that indexOf takes two arguments- the string to match, and the character index to start looking from. You can break the string at the first space after 10 characters.

每个人似乎都忘记了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
*/

#5


8  

Lodash has a function specifically written for this: _.truncate

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...'

#6


7  

Based on NT3RP answer which does not handle some corner cases, I've made this code. It guarantees to not return a text with a size > maxLength event an ellipsis ... was added at the end.

基于NT3RP答案,它不处理一些特殊情况,我编写了这段代码。它保证不会返回一个具有> maxLength事件大小和省略号的文本…最后添加。

This also handle some corner cases like a text which have a single word being > 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;
}

I guess you can easily remove the jquery dependency if this bothers you.

如果这让您感到困扰,我想您可以轻松地删除jquery依赖项。

#7


2  

I took a different approach. While I needed a similar result I wanted to keep my return value less than the specified length.

我采取了不同的方法。虽然我需要类似的结果,但我希望使返回值小于指定的长度。

function wordTrim(value, length, overflowSuffix) {
    value = value.trim();
    if (value.length <= length) return value;
    var strAry = value.split(' ');
    var retString = strAry[0];
    for (var i = 1; i < strAry.length; i++) {
        if (retString.length >= length || retString.length + strAry[i].length + 1 > length) break;
        retString += " " + strAry[i];
    }
    return retString + (overflowSuffix || '');
}

Edit I refactored it a bit here: JSFiddle Example. It rejoins the original array instead of concatenating.

编辑我在这里重构了一点:JSFiddle示例。它对原始数组进行排序而不是连接。

function wordTrim(value, length, overflowSuffix) {
    if (value.length <= length) return value;
    var strAry = value.split(' ');
    var retLen = strAry[0].length;
    for (var i = 1; i < strAry.length; i++) {
        if(retLen == length || retLen + strAry[i].length + 1 > length) break;
        retLen+= strAry[i].length + 1
    }
    return strAry.slice(0,i).join(' ') + (overflowSuffix || '');
}

#8


1  

function shorten(str,n) {
  return (str.match(RegExp(".{"+n+"}\\S*"))||[str])[0];
}

shorten("Hello World", 3); // "Hello"

// SHORTEN STRING TO WHOLE WORDS
function shorten(s,l) {
  return (s.match(new RegExp(".{"+l+"}\\S*"))||[s])[0];
}

console.log( shorten("The quick brown fox jumps over the lazy dog", 6) ); // "The quick"

#9


0  

You can trim spaces with this:

你可以这样装饰空间:

var trimmedString = flabbyString.replace(/^\s*(.*)\s*$/, '$1');

#10


0  

This excludes the final word instead of including it.

这排除了最后一个词,而不是包括它。

function smartTrim(str, length, delim, appendix) {
    if (str.length <= length) return str;

    var trimmedStr = str.substr(0, length+delim.length);

    var lastDelimIndex = trimmedStr.lastIndexOf(delim);
    if (lastDelimIndex >= 0) trimmedStr = trimmedStr.substr(0, lastDelimIndex);

    if (trimmedStr) trimmedStr += appendix;
    return trimmedStr;
}

Usage:

用法:

smartTrim(yourString, 11, ' ', ' ...')
"The quick ..."

#11


0  

For what it's worth I wrote this to truncate to word boundary without leaving punctuation or whitespace at the end of the string:

值得注意的是,我写这篇文章是为了截断单词边界,而不在字符串末尾留下标点或空格:

function truncateStringToWord(str, length, addEllipsis)
{
    if(str.length <= length)
    {
        // provided string already short enough
        return(str);
    }

    // cut string down but keep 1 extra character so we can check if a non-word character exists beyond the boundary
    str = str.substr(0, length+1);

    // cut any non-whitespace characters off the end of the string
    if (/[^\s]+$/.test(str))
    {
        str = str.replace(/[^\s]+$/, "");
    }

    // cut any remaining non-word characters
    str = str.replace(/[^\w]+$/, "");

    var ellipsis = addEllipsis && str.length > 0 ? '&hellip;' : '';

    return(str + ellipsis);
}

var testString = "hi stack overflow, how are you? Spare";
var i = testString.length;

document.write('<strong>Without ellipsis:</strong><br>');

while(i > 0)
{
  document.write(i+': "'+ truncateStringToWord(testString, i) +'"<br>');
  i--;
}

document.write('<strong>With ellipsis:</strong><br>');

i = testString.length;
while(i > 0)
{
  document.write(i+': "'+ truncateStringToWord(testString, i, true) +'"<br>');
  i--;
}

#12


0  

I'm late to the party, but here's a small and easy solution I came up with to return an amount of words.

我参加聚会迟到了,但我想出了一个简单的办法来回话。

It's not directly related to your requirement of characters, but it serves the same outcome that I believe you were after.

它与你对角色的要求没有直接关系,但它的结果与我相信你所追求的是一样的。

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, '...'));

See the working example here: https://jsfiddle.net/bx7rojgL/

请参见这里的工作示例:https://jsfiddle.net/bx7rojgL/

#13


-1  

Updated from @NT3RP I found that if the string happens to hit a space first time around it will end up deleting that word making your string one word shorter than it can be. So I just threw in an if else statement to check that the maxLength doesn't fall on a space.

@NT3RP更新后,我发现如果字符串第一次碰到空格,它会删除这个单词,使你的字符串变短一个单词。所以我加入了if else语句来检查maxLength是否落在空格上。

codepen.io

codepen.io

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

if (yourString[maxLength] !== " ") {

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

alert(trimmedString)

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

else {
  var trimmedString = yourString.substr(0, maxLength);
}

alert(trimmedString)

#1


120  

If I understand correctly, you want to shorten a string to a certain length (e.g. shorten "The quick brown fox jumps over the lazy dog" to, say, 6 characters without cutting off any word).

如果我理解正确的话,你想要把一根绳子缩短到一定的长度(例如,把“快速棕色狐狸跳过懒狗”缩短为6个字符而不剪掉任何单词)。

If this is the case, you can try something like the following:

如果是这样的话,你可以试试以下方法:

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(" ")))

#2


68  

There are lots of ways to do it, but a regular expression is a useful one line method:

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

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

This expressions returns the first 11 (any) characters plus any subsequent non-space characters.

这个表达式返回前11个(任意)字符加上任何后续的非空格字符。

Example script:

示例脚本:

<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>

Output:

输出:

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

#3


21  

I am kind of surprised that for a simple problem like this there are so many answers that are difficult to read and some, including the chosen one, do not work .

对于这样一个简单的问题,有这么多难以阅读的答案,而有些答案,包括所选的答案,却不管用,我有点惊讶。

I usually want the result string to be at most maxLen characters. I also use this same function to shorten the slugs in URLs.

我通常希望结果字符串最多为maxLen字符。我还使用这个函数来缩短url中的slugs。

str.lastIndexOf(searchValue[, fromIndex]) takes a second parameter that is the index at which to start searching backwards in the string making things efficient and simple.

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

This is a sample output:

这是一个输出示例:

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"

And for the slug:

和鼻涕虫:

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"

#4


17  

Everyone seems to forget that indexOf takes two arguments- the string to match, and the character index to start looking from. You can break the string at the first space after 10 characters.

每个人似乎都忘记了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
*/

#5


8  

Lodash has a function specifically written for this: _.truncate

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...'

#6


7  

Based on NT3RP answer which does not handle some corner cases, I've made this code. It guarantees to not return a text with a size > maxLength event an ellipsis ... was added at the end.

基于NT3RP答案,它不处理一些特殊情况,我编写了这段代码。它保证不会返回一个具有> maxLength事件大小和省略号的文本…最后添加。

This also handle some corner cases like a text which have a single word being > 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;
}

I guess you can easily remove the jquery dependency if this bothers you.

如果这让您感到困扰,我想您可以轻松地删除jquery依赖项。

#7


2  

I took a different approach. While I needed a similar result I wanted to keep my return value less than the specified length.

我采取了不同的方法。虽然我需要类似的结果,但我希望使返回值小于指定的长度。

function wordTrim(value, length, overflowSuffix) {
    value = value.trim();
    if (value.length <= length) return value;
    var strAry = value.split(' ');
    var retString = strAry[0];
    for (var i = 1; i < strAry.length; i++) {
        if (retString.length >= length || retString.length + strAry[i].length + 1 > length) break;
        retString += " " + strAry[i];
    }
    return retString + (overflowSuffix || '');
}

Edit I refactored it a bit here: JSFiddle Example. It rejoins the original array instead of concatenating.

编辑我在这里重构了一点:JSFiddle示例。它对原始数组进行排序而不是连接。

function wordTrim(value, length, overflowSuffix) {
    if (value.length <= length) return value;
    var strAry = value.split(' ');
    var retLen = strAry[0].length;
    for (var i = 1; i < strAry.length; i++) {
        if(retLen == length || retLen + strAry[i].length + 1 > length) break;
        retLen+= strAry[i].length + 1
    }
    return strAry.slice(0,i).join(' ') + (overflowSuffix || '');
}

#8


1  

function shorten(str,n) {
  return (str.match(RegExp(".{"+n+"}\\S*"))||[str])[0];
}

shorten("Hello World", 3); // "Hello"

// SHORTEN STRING TO WHOLE WORDS
function shorten(s,l) {
  return (s.match(new RegExp(".{"+l+"}\\S*"))||[s])[0];
}

console.log( shorten("The quick brown fox jumps over the lazy dog", 6) ); // "The quick"

#9


0  

You can trim spaces with this:

你可以这样装饰空间:

var trimmedString = flabbyString.replace(/^\s*(.*)\s*$/, '$1');

#10


0  

This excludes the final word instead of including it.

这排除了最后一个词,而不是包括它。

function smartTrim(str, length, delim, appendix) {
    if (str.length <= length) return str;

    var trimmedStr = str.substr(0, length+delim.length);

    var lastDelimIndex = trimmedStr.lastIndexOf(delim);
    if (lastDelimIndex >= 0) trimmedStr = trimmedStr.substr(0, lastDelimIndex);

    if (trimmedStr) trimmedStr += appendix;
    return trimmedStr;
}

Usage:

用法:

smartTrim(yourString, 11, ' ', ' ...')
"The quick ..."

#11


0  

For what it's worth I wrote this to truncate to word boundary without leaving punctuation or whitespace at the end of the string:

值得注意的是,我写这篇文章是为了截断单词边界,而不在字符串末尾留下标点或空格:

function truncateStringToWord(str, length, addEllipsis)
{
    if(str.length <= length)
    {
        // provided string already short enough
        return(str);
    }

    // cut string down but keep 1 extra character so we can check if a non-word character exists beyond the boundary
    str = str.substr(0, length+1);

    // cut any non-whitespace characters off the end of the string
    if (/[^\s]+$/.test(str))
    {
        str = str.replace(/[^\s]+$/, "");
    }

    // cut any remaining non-word characters
    str = str.replace(/[^\w]+$/, "");

    var ellipsis = addEllipsis && str.length > 0 ? '&hellip;' : '';

    return(str + ellipsis);
}

var testString = "hi stack overflow, how are you? Spare";
var i = testString.length;

document.write('<strong>Without ellipsis:</strong><br>');

while(i > 0)
{
  document.write(i+': "'+ truncateStringToWord(testString, i) +'"<br>');
  i--;
}

document.write('<strong>With ellipsis:</strong><br>');

i = testString.length;
while(i > 0)
{
  document.write(i+': "'+ truncateStringToWord(testString, i, true) +'"<br>');
  i--;
}

#12


0  

I'm late to the party, but here's a small and easy solution I came up with to return an amount of words.

我参加聚会迟到了,但我想出了一个简单的办法来回话。

It's not directly related to your requirement of characters, but it serves the same outcome that I believe you were after.

它与你对角色的要求没有直接关系,但它的结果与我相信你所追求的是一样的。

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, '...'));

See the working example here: https://jsfiddle.net/bx7rojgL/

请参见这里的工作示例:https://jsfiddle.net/bx7rojgL/

#13


-1  

Updated from @NT3RP I found that if the string happens to hit a space first time around it will end up deleting that word making your string one word shorter than it can be. So I just threw in an if else statement to check that the maxLength doesn't fall on a space.

@NT3RP更新后,我发现如果字符串第一次碰到空格,它会删除这个单词,使你的字符串变短一个单词。所以我加入了if else语句来检查maxLength是否落在空格上。

codepen.io

codepen.io

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

if (yourString[maxLength] !== " ") {

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

alert(trimmedString)

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

else {
  var trimmedString = yourString.substr(0, maxLength);
}

alert(trimmedString)