Javascript 字数统计被截断
我有一个 ID 为“shortblogpost”的 div。我想数到第 27 个单词,然后停下来并在末尾添加“...”。
我正在尝试以下代码。问题是,它计算字母而不是单词。我认为它使用 jQuery 而不是直接使用 JavaScript?
由于各种服务器原因,我需要使用 JavaScript,但
<script type="text/javascript">
var limit = 100,
text = $('div.shortblogpost').text().split(/\s+/),
word,
letter_count = 0,
trunc = '',
i = 0;
while (i < text.length && letter_count < limit) {
word = text[i++];
trunc += word+' ';
letter_count = trunc.length-1;
}
trunc = $.trim(trunc)+'...';
console.log(trunc);
</script>
需要提前全部获取帮助。
I have a div with an ID "shortblogpost". I would like to count up to 27th word then stop and add "..." at the end.
I was trying the following code. Problem, Its counting letters and not words. I think its using jQuery and not strait up JavaScript?
I need to use JavaScript for various server reasons only
<script type="text/javascript">
var limit = 100,
text = $('div.shortblogpost').text().split(/\s+/),
word,
letter_count = 0,
trunc = '',
i = 0;
while (i < text.length && letter_count < limit) {
word = text[i++];
trunc += word+' ';
letter_count = trunc.length-1;
}
trunc = $.trim(trunc)+'...';
console.log(trunc);
</script>
Ty all in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
截断函数。
使用: truncate('这是对该函数的测试', 2);
返回: 这是...
使用: truncate('这是此函数的测试', 5, '+++');
返回:这是对+++的测试
编辑:
通过OP参数快速而肮脏地实现:
Truncate function.
Use: truncate('This is a test of this function', 2);
Returns: This is...
Use: truncate('This is a test of this function', 5, '+++');
Returns: This is a test of+++
Edit:
Quick and dirty implement by parameters of OP:
这可以通过一行代码完成:
或者,您可以将其设为一个函数:
因此,要使其适用于您的代码,您可以执行以下操作:
This can be done in one line of code:
Or, you can make it a function:
So, to make this work for your code, you can do:
循环逐字附加,而(有单词&&字母数低于限制)。您唯一需要做的就是用“&&字数低于限制”替换第二个条件。
将此伪代码转换为 JS 应该很简单......
The loop is appending word by word, while (there are words && the letter count is lower than a limit). The only thing you need to do is replace the second condition with "&& the word count is lower than a limit".
Converting this pseudocode to JS should be trivial...
这个怎么样? jsfiddle
html:
javascript:
How about this? jsfiddle
html:
javascript:
这应该有效:
This should work: