我想使用 JavaScript 用省略号截断文本或行

我正在寻找一个简单的脚本,可以用省略号(...)截断字符串

我想截断像 'this is a very long string''this is a ve...'这样的东西

我不想使用 CSS 或 PHP。

161964 次浏览

Something like:

var line = "foo bar lol";
line.substring(0, 5) + '...' // gives "foo b..."

HTML with JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p>


<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

The result will be:

My long lo...

Cheers

G.

function truncate(input) {
if (input.length > 5) {
return input.substring(0, 5) + '...';
}
return input;
};

or in ES6

const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input;

If you want to cut a string for a specifited length and add dots use

// Length to cut
var lengthToCut = 20;


// Sample text
var text = "The quick brown fox jumps over the lazy dog";


// We are getting 50 letters (0-50) from sample text
var cutted = text.substr(0, lengthToCut );
document.write(cutted+"...");

Or if you want to cut not by length but with words count use:

// Number of words to cut
var wordsToCut = 3;


// Sample text
var text = "The quick brown fox jumps over the lazy dog";


// We are splitting sample text in array of words
var wordsArray = text.split(" ");


// This will keep our generated text
var cutted = "";
for(i = 0; i < wordsToCut; i++)
cutted += wordsArray[i] + " "; // Add to cutted word with space


document.write(cutted+"...");

Good luck...

function truncate(string, length, delimiter) {
delimiter = delimiter || "&hellip;";
return string.length > length ? string.substr(0, length) + delimiter : string;
};


var long = "Very long text here and here",
short = "Short";


truncate(long, 10); // -> "Very long ..."
truncate(long, 10, ">>"); // -> "Very long >>"
truncate(short, 10); // -> "Short"

KooiInc has a good answer to this. To summarise:

String.prototype.trunc =
function(n){
return this.substr(0,n-1)+(this.length>n?'&hellip;':'');
};

Now you can do:

var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not...

And if you prefer it as a function, as per @AlienLifeForm's comment:

function truncateWithEllipses(text, max)
{
return text.substr(0,max-1)+(text.length>max?'&hellip;':'');
}

Full credit goes to KooiInc for this.

This will put the ellipsis in the center of the line:

function truncate( str, max, sep ) {


// Default to 10 characters
max = max || 10;


var len = str.length;
if(len > max){


// Default to elipsis
sep = sep || "...";


var seplen = sep.length;


// If seperator is larger than character limit,
// well then we don't want to just show the seperator,
// so just show right hand side of the string.
if(seplen > max) {
return str.substr(len - max);
}


// Half the difference between max and string length.
// Multiply negative because small minus big.
// Must account for length of separator too.
var n = -0.5 * (max - len - seplen);


// This gives us the centerline.
var center = len/2;


var front = str.substr(0, center - n);
var back = str.substr(len - center + n); // without second arg, will automatically go to end of line.


return front + sep + back;


}


return str;
}


console.log( truncate("123456789abcde") ); // 123...bcde (using built-in defaults)
console.log( truncate("123456789abcde", 8) ); // 12...cde (max of 8 characters)
console.log( truncate("123456789abcde", 12, "_") ); // 12345_9abcde (customize the separator)

For example:

1234567890 --> 1234...8910

And:

A really long string --> A real...string

Not perfect, but functional. Forgive the over-commenting... for the noobs.

Easiest and flexible way: JSnippet DEMO

Function style:

function truncString(str, max, add){
add = add || '...';
return (typeof str === 'string' && str.length > max ? str.substring(0,max)+add : str);
};

Prototype:

String.prototype.truncString = function(max, add){
add = add || '...';
return (this.length > max ? this.substring(0,max)+add : this);
};

Usage:

str = "testing with some string see console output";


//By prototype:
console.log(  str.truncString(15,'...')  );


//By function call:
console.log(  truncString(str,15,'...')  );

Try this

function shorten(text, maxLength, delimiter, overflow) {
delimiter = delimiter || "&hellip;";
overflow = overflow || false;
var ret = text;
if (ret.length > maxLength) {
var breakpoint = overflow ? maxLength + ret.substr(maxLength).indexOf(" ") : ret.substr(0, maxLength).lastIndexOf(" ");
ret = ret.substr(0, breakpoint) + delimiter;
}
return ret;
}


$(document).ready(function() {
var $editedText = $("#edited_text");
var text = $editedText.text();
$editedText.text(shorten(text, 33, "...", false));
});

Checkout a working sample on Codepen http://codepen.io/Izaias/pen/QbBwwE

This will limit it to however many lines you want it limited to and is responsive

An idea that nobody has suggested, doing it based on the height of the element and then stripping it back from there.

Fiddle - https://jsfiddle.net/hutber/u5mtLznf/ <- ES6 version

But basically you want to grab the line height of the element, loop through all the text and stop when its at a certain lines height:

'use strict';


var linesElement = 3; //it will truncate at 3 lines.
var truncateElement = document.getElementById('truncateme');
var truncateText = truncateElement.textContent;


var getLineHeight = function getLineHeight(element) {
var lineHeight = window.getComputedStyle(truncateElement)['line-height'];
if (lineHeight === 'normal') {
// sucky chrome
return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
} else {
return parseFloat(lineHeight);
}
};


linesElement.addEventListener('change', function () {
truncateElement.innerHTML = truncateText;
var truncateTextParts = truncateText.split(' ');
var lineHeight = getLineHeight(truncateElement);
var lines = parseInt(linesElement.value);


while (lines * lineHeight < truncateElement.clientHeight) {
console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight);
truncateTextParts.pop();
truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
}
});

CSS

#truncateme {
width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}

For preventing the dots in the middle of a word or after a punctuation symbol.

let parseText = function(text, limit){
if (text.length > limit){
for (let i = limit; i > 0; i--){
if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {
return text.substring(0, i) + '...';
}
}
return text.substring(0, limit) + '...';
}
else
return text;
};
    

    

console.log(parseText("1234567 890",5))  // >> 12345...
console.log(parseText("1234567 890",8))  // >> 1234567...
console.log(parseText("1234567 890",15)) // >> 1234567 890