【问题标题】:Breaking Down a String into Maximum Character Sections in JavaScript在 JavaScript 中将字符串分解为最大字符段
【发布时间】:2017-08-01 17:37:54
【问题描述】:

我需要将 JavaScript 中的字符串分成不超过 100 个字符的块,同时保持单词之间的中断。我在自己的个人库中有一个函数可以将字符串分块成 100 个字符的部分,但我似乎无法理解如何调整它以避免在单词中间分裂。我认为可以使用正则表达式或其他东西来管理某些东西,但它并没有出现在我身上。对任何解决方案的一个警告是,它必须是纯 JavaScript,而不是 jQuery,并且环境无法访问与浏览器相关的全局变量。

-- 编辑--

好的,我已经写了一些代码,但是我得到了奇怪的结果......

function chunkify(str) {
    var wsRegEx = /\S/;
    var wsEndRegEx = /\s$/;
    var wsStartRegEx = /^\s/;
    var chunks = new Array();
    var startIndex = 0;
    var endIndex = 100;
    var totalChar = 0;
    while (true) {
        if (totalChar >= str.length) break;
        var chunk = str.substr(startIndex,endIndex-startIndex);
        while (wsStartRegEx.test(chunk)) {
            startIndex++;
            endIndex++;
            totalChar++;
            chunk = str.substr(startIndex,endIndex-startIndex);
        }
        if (!wsEndRegEx.test(chunk)) {
            while (wsRegEx.test(chunk.charAt(endIndex))) {
                endIndex--;
            }
            chunk = str.substr(startIndex,endIndex-startIndex);
        }
        chunks.push(chunk);
        totalChar += chunk.length;
        startIndex = endIndex;
        endIndex += 100;
    }
    return chunks;
}

我发布的上一个版本没有正确计算块数,但是这个似乎确实正确中断的版本现在中断了中间词。

-- 编辑#2--

我想我现在做得很好。这似乎可以解决问题:

function chunkify(str) {
    var wsRegEx = /\S/;
    var chunks = new Array();
    var startIndex = 0;
    var endIndex = 100;
    while (startIndex < str.length) {
        while (wsRegEx.test(str.charAt(endIndex))) {
            endIndex--;
        }
        if (!wsRegEx.test(str.charAt(startIndex)))
            startIndex++;
        chunks.push(str.substr(startIndex, endIndex - startIndex));
        startIndex = endIndex;
        endIndex += 100;
    }
    return chunks;
}

有没有更清洁的方法来做到这一点,或者我是否让它尽可能高效?

【问题讨论】:

  • 到目前为止你都尝试过什么?有代码吗?

标签: javascript string


【解决方案1】:

我已尝试为您说明这一点,因此您了解一种可以完成的方法

function chunkify (str) {
  var chunks = [];
  var startIdx = 0, endIdx;
  //Traverse through the string, 100 characters at a go
  //If the character in the string after the next 100 (str.charAt(x)) is not a whitespace char, try the previous character(s) until a whitespace character is found.
  //Split on the whitespace character and add it to chunks
  return chunks
}

【讨论】:

  • 这基本上会在 do/while 循环中处理吗?
  • @MichaelMcCauley 可能。您将需要使用循环机制,其中在 javascript 和 jquery 中有几种
  • 不能使用jQuery,在工作环境中不可用。看起来这很可能是一对嵌套循环。一个循环处理整体结构,一个内部循环沿着字符串向后滑动以找到最后一个空白字符。
【解决方案2】:

这是一种使用正则表达式的方法:

chunks = str.match(/.{1,100}/g);

【讨论】:

    猜你喜欢
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    相关资源
    最近更新 更多