te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>blogs - Javascript word count cut off - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

blogs - Javascript word count cut off - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Feb 10, 2011 at 21:03 webmaster alex lwebmaster alex l 6634 gold badges17 silver badges32 bronze badges 1
  • lodash truncate may be helpful. doc – tinystone Commented Dec 9, 2023 at 23:34
Add a ment  | 

5 Answers 5

Reset to default 8

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>

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

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

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

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() + "...";
发布评论

评论列表(0)

  1. 暂无评论