javascript - 从 javascript String 创建一个包含 X 个单词的数组

标签 javascript arrays regex

你好 Stack 社区,

我正在尝试实现一个简单的 javascript 函数来首先计算给定字符串值中的单词总数。

在此之后,我不想将 X 个单词存储到一个数组中,以便能够循环使用它周围的其他 html 元素。

例如,我有这个字符串:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis feugiat sollicitudin lacus, nec pulvinar quam scelerisque at. Phasellus ut tellus scelerisque, fringilla ligula a, commodo odio. Aenean mattis eros sed purus iaculis, at pellentesque ligula luctus. Pellentesque luctus augue ut quam consequat rhoncus. In at dolor sed ipsum ullamcorper fermentum. Pellentesque porta convallis nisl vitae cursus. Maecenas luctus libero sit amet efficitur consequat. Suspendisse nec luctus dolor. Fusce sit amet scelerisque erat. Aenean ac tristique nisl. Etiam in est purus. In magna nunc, viverra nec ante quis, aliquam venenatis sem.

这是我实际处理的代码。 (我只参加了必修部分)。

// Var for Word max
    var wordsMaxFirstPage = 40;
    var wordsMaxOthersPages = 50;

    // Default field (My String example)
    var defaultField = $(this).find('.c_6937 .textarea .value');

    // Count the number of words for this form
    var countLengthOfCommentPage = defaultField.text().split(' ').length;

    // Creat Array of the comment splits by Maximum words per page
    var chunks = [];
    for (var i = 0, charsLength = countLengthOfCommentPage; i < charsLength; i += wordsMaxFirstPage) {
        chunks.push(defaultField.html().substring(i, i + wordsMaxOthersPages));
    }


    // Execute Array to build the new HTML
    for (var key in chunks) {
        if (chunks.hasOwnProperty(key)) {

            $(this).find('.c_6937').append('<div class="value line_'+key+'" style="font-size: 20px; margin: 0px; line-height: 26px; font-family: Times, serif; font-weight: normal;">' + chunks[key] + '</div>');

            console.log(key + " -> " + chunks[key]);
        }
    }


    // Debug
    console.log(countLengthOfCommentPage);

对我来说,事情变得复杂而难以理解的地方是我构建数组的地方。是的,我知道,我使用 substring 方法,这个方法实际上适用于字符。

我的问题很简单。有什么方法可以使用正则表达式函数构建数组,还是我只是遗漏了一些非常简单的东西?

最佳答案

实际上您已经在创建数组,但没有保存它 ;)。

Javascript 中的 split() 函数拆分给定的字符串并创建一个包含结果片段的数组。

我建议替换这一行:

var countLengthOfCommentPage = defaultField.text().split(' ').length;

有了这两个:

var chunks = defaultField.text().split(' ');
var countLengthOfCommentPage = chunks.length;

如果这能解决您的问题,请告诉我。

更新

我的第一个建议是在每个 chunks 元素中给你一个单词,这不是你的解决方案。

您发布的原始代码的问题是构建数组的循环没有考虑每个单词的长度。

你可以像这样构建数组:

// split the text into separate words
var words = defaultField.text().split(' ');

//read total number of words
var totalWordsCount = words.length;
//maximum number of words per page allowed, set to 10 as example
var wordsCountPerPage = 10;
var chunks = [];

// in each iteration "i" points to the first word in the new page, so it's 0, 11, 21 etc.
for (var i = 0; i < totalWordsCount; i+=wordsCountPerPage) {
    //'slice()' function gets words for the current line, then they're concatenated with 'join()'
    //'Math.min()' function is used to make sure that appropriate number of words are taken for the last page
    chunks.push(words.slice(i, Math.min(i+wordsCountPerPage, totalWordsCount)).join(' '));
}

我已经更新了 jsFiddle,它似乎按预期工作。如果这能解决您的问题,请告诉我。

更新二

在评论中,您还要求在达到每页字数限制之前检测最后一句话的结尾,以便尽可能在页面上显示完整的句子。此 jsFiddle 已更新为以这种方式工作:http://jsfiddle.net/gbb2ae4g/17/ .这个想法是以类似于以前版本的方式找到预期的页面结尾,然后搜索以 结尾的最后一个词并相应地调整页面上的词数。此代码假定 始终后跟一个空格 字符,除非它是文本中的最后一个字符。

我还更新了作为先前答案给出的代码(第一次更新),因为它错误地执行了页尾检查。

关于javascript - 从 javascript String 创建一个包含 X 个单词的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32317765/

相关文章:

arrays - 数组操作给我合并表

javascript - chrome.declarativeContent.PageStateMatcher 中的正则表达式

php - 使用 PHP 在 CSS 中搜索内容

javascript - WordPress add_option 查询返回空白参数

javascript - lodash删除嵌套数组元素的方法

javascript - Firebase 的云功能 : how to reference a key in a list that has been just pushed

java - 存储字符串数组唯一列表的最佳方式

regex - 有没有更好的方法在 Emacs 中进行正则表达式搜索和删除?

javascript - jquery 选择 this.parent 之外的新元素

javascript - Tus服务器与神社集成 "Dealing with large uploads filesize > 1 gb"