Javascript字数切断

web*_*x l 4 javascript blogs word-count

我有一个ID为"shortblogpost"的div.我想数到第27个字然后停止并在最后加上"......".

我正在尝试以下代码.问题,它是计数字母而不是单词.我认为它使用jQuery而不是strait 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>
Run Code Online (Sandbox Code Playgroud)

Ty提前提供任何帮助.

Chr*_*ker 7

截断功能.

使用: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(' ');
}
Run Code Online (Sandbox Code Playgroud)

编辑: OP参数的快速和脏实现:

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

var ele = document.getElementById('shortblogpost');
ele.innerHTML = truncate(ele.innerHTML, 20);
</script>
Run Code Online (Sandbox Code Playgroud)


gil*_*ly3 5

这可以在一行代码中完成:

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

或者,你可以使它成为一个功能:

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

因此,为了使您的代码能够正常工作,您可以:

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
Run Code Online (Sandbox Code Playgroud)