如果我理解正确的话,你需要将一个字符串缩短到一定长度(例如,在不删除任何单词的情况下将 "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(" ")))
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
*/
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;
}
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)
// 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"
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...'
// 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));
}
这是一个样本输出:
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"
至于鼻涕虫:
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"
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 ? '…' : '';
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--;
}
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, '...'));
const text = "The string that I want to truncate!";
const truncate = (str, len) => str.substring(0, (str + ' ').lastIndexOf(' ', len));
console.log(truncate(text, 14));
我来晚了,但我认为这个函数完全符合 OP 的要求。您可以很容易地为不同的结果更改 SENTENT 和 LIMIT 值。
function breakSentence(word, limit) {
const queue = word.split(' ');
const list = [];
while (queue.length) {
const word = queue.shift();
if (word.length >= limit) {
list.push(word)
}
else {
let words = word;
while (true) {
if (!queue.length ||
words.length > limit ||
words.length + queue[0].length + 1 > limit) {
break;
}
words += ' ' + queue.shift();
}
list.push(words);
}
}
return list;
}
const SENTENCE = 'the quick brown fox jumped over the lazy dog';
const LIMIT = 11;
// get result
const words = breakSentence(SENTENCE, LIMIT);
// transform the string so the result is easier to understand
const wordsWithLengths = words.map((item) => {
return `[${item}] has a length of - ${item.length}`;
});
console.log(wordsWithLengths);
这个代码片段的输出是 LIMIT 为11的地方:
[ '[the quick] has a length of - 9',
'[brown fox] has a length of - 9',
'[jumped over] has a length of - 11',
'[the lazy] has a length of - 8',
'[dog] has a length of - 3' ]
function solution(message, k) {
if(!message){
return ""; //when message is empty
}
const messageWords = message.split(" ");
let result = messageWords[0];
if(result.length>k){
return ""; //when length of first word itself is greater that k
}
for(let i = 1; i<messageWords.length; i++){
let next = result + " " + messageWords[i];
if(next.length<=k){
result = next;
}else{
break;
}
}
return result;
}
console.log(solution("this is a long string i cant display", 10));
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));