我想使用 JavaScript 截断带有省略号的文本或行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4700226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I want to truncate a text or line with ellipsis using JavaScript
提问by Dollar Friend
I'm looking for a simple script which can truncate a string with ellipsis (...)
我正在寻找一个简单的脚本,它可以用省略号 (...)
I want to truncate something like 'this is a very long string'
to 'this is a ve...'
我想截断像'this is a very long string'
到'this is a ve...'
I don't want to use CSS or PHP.
我不想使用 CSS 或 PHP。
回答by El Ronnoco
function truncate(input) {
if (input.length > 5)
return input.substring(0,5) + '...';
else
return input;
};
or newer style terser JS...
或更新样式的 terser JS ...
const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input;
回答by Jarrod
KooiInc has a good answer to this. To summarise:
KooiInc 对此有一个很好的回答。总结一下:
String.prototype.trunc =
function(n){
return this.substr(0,n-1)+(this.length>n?'…':'');
};
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:
如果你更喜欢它作为一个函数,根据@AlienLifeForm 的评论:
function truncateWithEllipses(text, max)
{
return text.substr(0,max-1)+(text.length>max?'…':'');
}
Full credit goes to KooiIncfor this.
对此,KooiInc 全权负责。
回答by Jarrod
Something like:
就像是:
var line = "foo bar lol";
line.substring(0, 5) + '...' // gives "foo b..."
回答by Jamie Hutber
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
小提琴 - https://jsfiddle.net/hutber/u5mtLznf/<- ES6 版本
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
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
}
回答by davidivad
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
回答by Shlomi Hassid
Easiest and flexible way: JSnippet DEMO
最简单灵活的方式: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,'...') );
回答by bob
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.
不完美,但功能齐全。原谅过度评论......对于菜鸟。
回答by Izaias
Try this
尝试这个
function shorten(text, maxLength, delimiter, overflow) {
delimiter = delimiter || "…";
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
在 Codepen http://codepen.io/Izaias/pen/QbBwwE上签出工作示例
回答by polarblau
function truncate(string, length, delimiter) {
delimiter = delimiter || "…";
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"
回答by Greg
HTML with JavaScript:
带有 JavaScript 的 HTML:
<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.
G。