在特定字符和最大长度(JS)处断开长字符串

时间:2016-05-26 21:00:59

标签: javascript

可能有一个答案者比我的更清洁,更有效,但我找不到。所以到目前为止,我确实为自己尝试了很多结果。



len([1,2,344])
^

TypeError: len is not a function
    at Object.<anonymous> (/private/var/folders/j6/3fs5_k3n17z_0j2xrwj6sphw0000gn/T/CodeRunner/Untitled 11.js:2:1)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3
&#13;
var str = "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay, Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy, Zulu"; // person name come from an Array()

var maxCount = 100;
var jki = Math.floor(str.length / maxCount);
var i = 0;
arr = [];
var startPoint = 0;
while (i <= jki) {
  i++;
  arr.push(str.slice(startPoint, str.slice((i * maxCount) - maxCount, i * maxCount).lastIndexOf(" ") - 1))
  startPoint = str.slice((i * maxCount) - maxCount, i * maxCount).lastIndexOf(" ");
}
console.log(arr);
&#13;
&#13;
&#13;

这样我得到的东西就像第一个好,第二个是空的??,接下来就是失事:-s:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

修改

我所寻找的是str的长度最多为100个字符,并且名称是完整的。

[
  "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay",
  "",
  "say, Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy, Zu"
] 

在此示例中[ "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay,", "Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy, Zulu" ] arr[0].length // 99

如果我们要为列表示例arr[1].length // 100

添加新名称
ZZ-top

在此示例中[ "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay,", "Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy,", "Zulu, ZZ-top" ] arr[0].length // 99arr[1].length // 95

arr[2].length // 12

有人能看到我错过的东西吗?

提前致谢!

3 个答案:

答案 0 :(得分:2)

所以我花时间按照你的标准让它真正发挥作用。所有步骤都在评论中解释。

&#13;
&#13;
var str = "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay, Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy, Zulu";
var maxCount = 100;
var splitNames = function(str, max){
    // ["person:","Amy,","bertha,",...]
    var names = str.split(' '),
        lines = [],
        line = 0,
        lineLength = 0;

    // loop through our array of names
    names.forEach(function(name){
        // if length is more than our max
        if(lineLength + name.length + 1 > max){
            line += 1; // move to next line
            lineLength = 0; // reset length counter
        } else {
            lineLength += 1; // add 1 for the space we'll add later
        }
        // make sure we add an empty array if there isn't one
        lines[line] = lines[line] || [];
        
        // add the current name
        lines[line].push(name);
        
        // add name length to the line length
        lineLength += name.length;
    });
    
    return lines.map(function(line){
        // join our names with a space (which we counted toward the length)
        return line.join(' ');
    });
}
console.log(splitNames(str, maxCount));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你想念的东西很少。最重要的一点是你应该从startPoint开始下一个切片,而不是从(i * maxCount) - maxCount开始。另一个重要的是,lastIndexOf将从切片的开始计数,而不是从原始字符串的开始计算(对于除第一个之外的所有切片,它将小于maxCount,然后小于startPoint)。这就是为什么第二个块是空的。结合第一个biggie,它使得最后一个块从“说”开始,因为它从前一个块中的最后一个空格的位置开始。

你也应该注意最后一个空格不要被最后一个空格切断,因为最后可能没有空格。并且还要处理可能没有空格的切片。最后,即使str.length / maxCount是精确整数,块的数量也可能不是Math.floor(str.length / maxCount)。

为了说明这一点,我采取了自由的方式来修复它,就像我看到你想要做的那样。

var str = "Persons: Amy, bertha, Charlie, Donkey, Evy, Felicia, Ghunter, Hercules, Indica, Jody, Katy, Linsay, Moony, Nigel, Opethry, Phil, Quinton, Ricial, Stefany, Trudy, Ursla, Vlinder, Wendy, Xion, Yvy, Zulu";
var maxCount = 100;
var jki = Math.floor(str.length / maxCount);
var arr = [];
var startPoint = 0;
while (startPoint < str.length) {
    while (startPoint < str.length && str[startPoint] == ',' ||  str[startPoint] == ' ') // chop leading commas and spaces off
    startPoint++;
    var nextSlice;
    var nextStart;
    if (startPoint + maxCount >= str.length) {
        // last chunk goes in completely
        nextSlice = str.slice(startPoint);
        nextStart = str.length;
    }
    else {
        // not last, chop of by last space if any
        nextSlice = str.slice(startPoint, startPoint + maxCount);
        nextStart = nextSlice.lastIndexOf(" ");
        if (nextStart <= 0) {
            nextStart = nextSlice.length;
        }
        else {
            nextStart -= 1;
        }
        nextStart += startPoint; // adjust for slice starting not at the beginning of str
     }
     arr.push(str.slice(startPoint, nextStart));
     startPoint = nextStart + 1;
}
console.log(arr);

答案 2 :(得分:0)

&#13;
&#13;
printABCS
&#13;
&#13;
&#13;