Javascript 用“...”替换太长的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7196804/
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
Replace too long strings with "..."
提问by user829237
Lets say we have a <div style="width:100px;">This text is too long to fit</div>
假设我们有一个 <div style="width:100px;">This text is too long to fit</div>
The text in the div is dynamic. And I'd like to force the text to fit in width and not break.
So i need some kind of functionality to test if the text is going to fit, and if it is not, then i'd like to display the portion of the text that will actually fit. And append ...
to the end.
div 中的文本是动态的。我想强制文本适应宽度而不是中断。所以我需要某种功能来测试文本是否适合,如果不是,那么我想显示实际适合的文本部分。并附...
加到最后。
Result for a too long text should be something like this: "This text is..."
太长文本的结果应该是这样的: "This text is..."
Is there some standard way of doing what i want? Either by javascript, jquery, jsp or java?
有什么标准的方法可以做我想做的事吗?是通过 javascript、jquery、jsp 还是 java?
Thanks!
谢谢!
Edit: Thanks for your quick and many answers! I was doing this in java by guessing how many characters would fit. It seemed like a less than optimal solution, so thats why i came here.
编辑:感谢您的快速回答!我在 java 中通过猜测适合多少个字符来做到这一点。这似乎是一个不太理想的解决方案,所以这就是我来到这里的原因。
The css solution is perfect for me. Its not that big of a deal that it doesnt work for firefox, since my clients all use ie anyway. :)
css 解决方案对我来说是完美的。它不适用于 Firefox 并不是什么大问题,因为我的客户都使用 ie。:)
回答by meo
you could do it with css3 using text-overflow:ellipsis
http://www.css3.com/css-text-overflow/
您可以使用http://www.css3.com/css-text-overflow/使用 css3text-overflow:ellipsis
or if you insist on using the js way, you can wrap the text-node inside your div and then compare the width of the wrap with the with of the parent.
或者,如果您坚持使用 js 方式,您可以将 text-node 包裹在 div 中,然后将包裹的宽度与父级的 with 进行比较。
回答by Mark Schultheiss
If you want to process the data you can use a function:
如果要处理数据,可以使用函数:
function TextAbstract(text, length) {
if (text == null) {
return "";
}
if (text.length <= length) {
return text;
}
text = text.substring(0, length);
last = text.lastIndexOf(" ");
text = text.substring(0, last);
return text + "...";
}
text = "I am not the shortest string of a short lenth with all these cows in here cows cows cows cows";
alert(TextAbstract(text,20));
EDIT: process all div with excess length in the text:
编辑:处理文本中长度过长的所有 div:
var maxlengthwanted=20;
$('div').each(function(){
if ($('div').text().length > maxlengthwanted)
$(this).text(TextAbstract($(this).text()));
});
EDIT: More compact version to process all div with excess length in the text, breaks on space.
编辑:更紧凑的版本来处理文本中所有长度过长的 div,在空间上中断。
function textAbstract(el, maxlength = 20, delimiter = " ") {
let txt = $(el).text();
if (el == null) {
return "";
}
if (txt.length <= maxlength) {
return txt;
}
let t = txt.substring(0, maxlength);
let re = /\s+\S*$/;
let m = re.exec(t);
t = t.substring(0, m.index);
return t + "...";
}
var maxlengthwanted = 23;
$('.makeshort').each(function(index, element) {
$(element).text(textAbstract(element, maxlengthwanted, " "));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="makeshort">This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">second This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">IBShort Wilson</div>
<div class="makeshort">another This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">more This is a fun thing to process, modification of this is going to just be soo much fun</div>
<span class="makeshort">Me also, a span that is a fun thing to process, modification of this is going to just be soo much fun</span>
<span class="makeshort">more This is a fun thing to process, modification of this is going to just be soo much fun</span>
<ul>
<li class="makeshort">li1 more This is a fun thing to process, modification of this is going to just be soo much fun</li>
<li class="makeshort">li 2 more This is a fun thing to process, modification of this is going to just be soo much fun</li>
<li class="makeshort">li 3 also moreThis	is	a fun thing to process, modification of this is going to just be soo much fun</li>
<li class="makeshort">li 4 also more This is fun thing to process, modification of this is going to just be soo much fun</li>
</ul>
回答by evilone
if(text.length > number_of_characters) {
text = text.substring(from, to);
}
回答by Dynki
One liner using JavaScript
一个使用 JavaScript 的班轮
The below truncates the string to 10 characters with an ellipsis. If the length of the truncated string is below the limit (10 in the example below) then no ellipsis is added to the output.
下面用省略号将字符串截断为 10 个字符。如果截断字符串的长度低于限制(在下面的示例中为 10),则不会在输出中添加省略号。
const output = "abcdefghijk".split('', 10).reduce((o, c) => o.length === 9 ? `${o}${c}...` : `${o}${c}` , '');
回答by James
A more likely situation is that you can't possibly know how many characters are going to fit in a dom element, given it has its own font and so on. CSS3 is not currently an option (for me anyway). So, I create a little div offscreen and keep jamming test strings into it until the width is correct:
更可能的情况是您不可能知道一个 dom 元素中将容纳多少字符,因为它有自己的字体等等。CSS3 目前不是一个选项(无论如何对我来说)。所以,我在屏幕外创建了一个小 div 并继续将测试字符串插入其中直到宽度正确:
var text = 'Try to fit this text into 100 pixels!';
var max_width = 100;
var test = document.createElement('div');
test.className = 'Same Class as your real element'; // give it the same font, etc as a normal button
test.style.width = 'auto';
test.style.position = 'absolute';
test.style.left = '-2000px';
document.body.appendChild(test);
test.innerHTML = text;
if ($(test).width() > max_width) {
for (var i=text.length; i >= 0; i--) {
test.innerHTML = text.substring(0, i) + '...';
if ($(test).width() <= max_width) {
text = text.substring(0, i) + '...';
break;
}
}
}
document.body.removeChild(test);
回答by Tuxedo Joe
Easiest way to shorten the variable using JavaScript:
使用 JavaScript 缩短变量的最简单方法:
function truncate(string, length){
if (string.length > length)
return string.substring(0,length)+'...';
else
return string;
};
Inspired by this answer: I want to truncate a text or line with ellipsis using JavaScript
受此答案的启发:我想使用 JavaScript 截断带有省略号的文本或行
回答by Joe
div {
text-overflow: ellipsis
}
Will be supported in FireFox 7 http://caniuse.com/#search=text-overflow
FireFox 7 将支持http://caniuse.com/#search=text-overflow
回答by Jared Ng
If you add an id
tag to the div, you can use document.getElementById("divid").innerHTML
to get the contents of the div. From there, you can use .length
to get the length of the string. If the length of the string is over a certain threshold, just take a substring and append a "...".
如果id
在 div 中添加标签,则可以使用document.getElementById("divid").innerHTML
来获取 div 的内容。从那里,您可以使用.length
来获取字符串的长度。如果字符串的长度超过某个阈值,只需取一个子字符串并附加一个“...”。
You should try to do this server-side if you can, though. Relying on Javascript/CSS to format it correctly for the user is a less than ideal solution.
不过,如果可以,您应该尝试在服务器端执行此操作。依靠 Javascript/CSS 为用户正确设置格式是一个不太理想的解决方案。
回答by sk.
Try the CSS text-overflowproperty.
试试 CSS text-overflow属性。