javascript - 在不破坏单词的情况下在 Javascript 中分块/拆分字符串

标签 javascript string

你好,

我想知道是否有一种简单的方法可以在不破坏单词的情况下分块/拆分字符串。

例如:

var input = "Lorem ipsum dolor sit amet, consectetur  adipiscing elit. Proin placerat, nisi nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

如果我在 80 个字符长处中断,应该返回这样的数组:

var output = ["Lorem ipsum dolor sit amet, consectetur  adipiscing elit. Proin placerat, nisi",
"nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero",
"eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor sit",
"amet, consectetur adipiscing elit."];

我发现那段代码非常好:

//http://phpjs.org/functions/chunk_split:369
function chunk_split (body, chunklen, end) {
    // Returns split line  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/chunk_split
    // +   original by: Paulo Freitas
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Theriault
    // *     example 1: chunk_split('Hello world!', 1, '*');
    // *     returns 1: 'H*e*l*l*o* *w*o*r*l*d*!*'
    // *     example 2: chunk_split('Hello world!', 10, '*');
    // *     returns 2: 'Hello worl*d!*'
    chunklen = parseInt(chunklen, 10) || 76;
    end = end || '\r\n';

    if (chunklen < 1) {
        return false;
    }

    return body.match(new RegExp(".{0," + chunklen + "}", "g")).join(end);
}

但我真的怀疑我能否修改它,以免单词被分成两半。有什么建议吗?

谢谢!

最佳答案

这里有一些蛮力代码可以做到这一点:

function splitIntoLines(input, len) {
    var i;
    var output = [];
    var lineSoFar = "";
    var temp;
    var words = input.split(' ');
    for (i = 0; i < words.length;) {
        // check if adding this word would exceed the len
        temp = addWordOntoLine(lineSoFar, words[i]);
        if (temp.length > len) {
            if (lineSoFar.length == 0) {
                lineSoFar = temp;     // force to put at least one word in each line
                i++;                  // skip past this word now
            }
            output.push(lineSoFar);   // put line into output
            lineSoFar = "";           // init back to empty
        } else {
            lineSoFar = temp;         // take the new word
            i++;                      // skip past this word now
        }
    }
    if (lineSoFar.length > 0) {
        output.push(lineSoFar);
    }
    return(output);
}

function addWordOntoLine(line, word) {
    if (line.length != 0) {
        line += " ";
    }
    return(line += word);
}

如果这个例程遇到一个比所需行长更长的单词,它会把它自己放在一行上,不会将其打散。

你可以在这里玩:http://jsfiddle.net/jfriend00/fbaLe/

关于javascript - 在不破坏单词的情况下在 Javascript 中分块/拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6632530/

相关文章:

javascript - 模拟 Javascript 面向对象编程 Stoyan Stefanov 书中的字符串 split()

python - 为什么我可以更新列表切片而不是 python 中的字符串切片?

javascript - Angular : ng-change mixed with jQuery not firing on second change

javascript - AngularJS 绑定(bind)问题

javascript - 使用 Javascript 将厘米转换为英寸

javascript - 无法修复购物车中的总计功能

javascript - 初始化对象内的数组,在 localStorage 中使用

PHP:如何拆分 UTF-8 字符串?

java - java中的二分查找字符串

android - SQLite 异常无法将 BLOB 转换为字符串