Javascript 字数统计被截断

发布于 2024-10-16 18:29:51 字数 641 浏览 2 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

旧梦荧光笔 2024-10-23 18:29:51

截断函数。

使用: truncate('这是对该函数的测试', 2);
返回: 这是...

使用: truncate('这是此函数的测试', 5, '+++');
返回:这是对+++的测试

function truncate (text, limit, append) {
    if (typeof text !== 'string')
        return '';
    if (typeof append == 'undefined')
        append = '...';
    var parts = text.split(' ');
    if (parts.length > limit) {
        // loop backward through the string
        for (var i = parts.length - 1; i > -1; --i) {
            // if i is over limit, drop this word from the array
            if (i+1 > limit) {
                parts.length = i;
            }
        }
        // add the truncate append text
        parts.push(append);
    }
    // join the array back into a string
    return parts.join(' ');
}

编辑:
通过OP参数快速而肮脏地实现:

<script type="text/javascript">
// put truncate function here...

var ele = document.getElementById('shortblogpost');
ele.innerHTML = truncate(ele.innerHTML, 20);
</script>

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+++

function truncate (text, limit, append) {
    if (typeof text !== 'string')
        return '';
    if (typeof append == 'undefined')
        append = '...';
    var parts = text.split(' ');
    if (parts.length > limit) {
        // loop backward through the string
        for (var i = parts.length - 1; i > -1; --i) {
            // if i is over limit, drop this word from the array
            if (i+1 > limit) {
                parts.length = i;
            }
        }
        // add the truncate append text
        parts.push(append);
    }
    // join the array back into a string
    return parts.join(' ');
}

Edit:
Quick and dirty implement by parameters of OP:

<script type="text/javascript">
// put truncate function here...

var ele = document.getElementById('shortblogpost');
ele.innerHTML = truncate(ele.innerHTML, 20);
</script>
狼性发作 2024-10-23 18:29:51

这可以通过一行代码完成:

myString.replace(/(([^\s]+\s+){27}).+/, "$1...");

或者,您可以将其设为一个函数:

function truncateString(s, wordCount)
{
    var expr = new RegExp("(([^\\s]+\\s+){" + wordCount + "}).+");
    return s.replace(expr, "$1...");
}

因此,要使其适用于您的代码,您可以执行以下操作:

var post = $('div.shortblogpost').text();  // get the text
post = postText.replace(/(([^\s]+\s+){27}).+/, "$1...");  // truncate the text
$('div.shortblogpost').text(post);  // update the post with the truncated text

This can be done in one line of code:

myString.replace(/(([^\s]+\s+){27}).+/, "$1...");

Or, you can make it a function:

function truncateString(s, wordCount)
{
    var expr = new RegExp("(([^\\s]+\\s+){" + wordCount + "}).+");
    return s.replace(expr, "$1...");
}

So, to make this work for your code, you can do:

var post = $('div.shortblogpost').text();  // get the text
post = postText.replace(/(([^\s]+\s+){27}).+/, "$1...");  // truncate the text
$('div.shortblogpost').text(post);  // update the post with the truncated text
佼人 2024-10-23 18:29:51

循环逐字附加,而(有单词&&字母数低于限制)。您唯一需要做的就是用“&&字数低于限制”替换第二个条件。

将此伪代码转换为 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...

ヤ经典坏疍 2024-10-23 18:29:51

这个怎么样? jsfiddle

html:

<div id='shortblogpost'>test test test test test test test test test test test</div>

javascript:

alert(document.getElementById('shortblogpost').innerHTML);
var numWordToDisplay = 3; //how many words u want to display in your case 27
var newArray = document.getElementById('shortblogpost').innerHTML.split(' ');
if(newArray.length >= numWordToDisplay )
    newArray.length = numWordToDisplay;
console.log(newArray.join(' ') + '...'); //test test test...

How about this? jsfiddle

html:

<div id='shortblogpost'>test test test test test test test test test test test</div>

javascript:

alert(document.getElementById('shortblogpost').innerHTML);
var numWordToDisplay = 3; //how many words u want to display in your case 27
var newArray = document.getElementById('shortblogpost').innerHTML.split(' ');
if(newArray.length >= numWordToDisplay )
    newArray.length = numWordToDisplay;
console.log(newArray.join(' ') + '...'); //test test test...
丿*梦醉红颜 2024-10-23 18:29:51

这应该有效:

var words = $('div.shortblogpost').text().replace( /\s/g, ' ' ).split( ' ' );
var result = "";
for( var w = 0 ; w < 27 ; w++ ) {
    if( words[w].length > 0 ) {
        result += words[w] + ' ';
    }
}
result = result.trim() + "...";

This should work:

var words = $('div.shortblogpost').text().replace( /\s/g, ' ' ).split( ' ' );
var result = "";
for( var w = 0 ; w < 27 ; w++ ) {
    if( words[w].length > 0 ) {
        result += words[w] + ' ';
    }
}
result = result.trim() + "...";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文