简体   繁体   English

从javascript字符串创建X个单词数的数组

[英]Create an array of X number of words from javascript String

Hello Stack community, 您好Stack社区,

I am trying to acheive a simple javascript function to first count the total number of words from a given string value. 我正在尝试实现一个简单的javascript函数,以首先从给定的字符串值计算单词的总数。

After this, I wan't to store X number of words into an array to be able to loop with additionnal html elements arround it. 在此之后,我将不将X个单词存储到数组中,以便能够与周围的其他html元素一起循环。

For exemple, I have this String : 例如,我有这个String:

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.

Here is the code I am actually working on. 这是我实际上正在处理的代码。 (I just took the required part). (我只是参加了必填部分)。

// 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);

The place where things get complicated to understand for me is where I build the array. 对我来说,事情变得复杂起来的地方就是我构建数组的地方。 Yes I know, I use substring Method and this method actually works with caracters. 是的,我知道,我使用子字符串方法,该方法实际上适用于角色。

My question is simple. 我的问题很简单。 Is there any way to build the array with a regex function or am I juste missing something very simple? 有什么方法可以使用正则表达式函数构建数组,还是我只是想丢失一些非常简单的东西?

Actually You are already creating the array, but not saving it ;). 实际上,您已经在创建数组,但尚未保存;)。

The split() function in Javascript splits the given string and creates an array with the resulting pieces. Javascript中的split()函数拆分给定的字符串,并创建一个包含结果片段的数组。

I would suggest replacing this line: 我建议替换此行:

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

With these two: 有了这两个:

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

Please let me know if this solves Your issue. 如果这解决了您的问题,请告诉我。

UPDATE UPDATE

My first suggestion would reault in giving You a single word in each of the chunks elements, which is not a solution in Your case. 我的第一个建议是在每个chunks元素中给您一个单词,这是re屈的,这不是您的解决方案。

The issue with the original code You posted is that thie loop building the array doesn't take each of the words' lengths into consideration. 您发布的原始代码的问题在于,构建数组的循环并没有考虑每个单词的长度。

You can build the array like this: 您可以像这样构建数组:

// 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(' '));
}

I've updated the jsFiddle and it seems to work as expected. 我已经更新了jsFiddle,它似乎按预期工作。 Please let me know if this solves Your issue. 如果这解决了您的问题,请告诉我。

UPDATE II 更新二

In the comments You also asked to detect end of the last sentence before words limit per page is reached in order ot display full sentences on page whenever possible. 在注释中,您还要求在达到每页字数限制之前检测最后一个句子的结尾,以便尽可能在页面上显示完整句子。 This jsFiddle is updated to work this way: http://jsfiddle.net/gbb2ae4g/17/ . 此jsFiddle已更新为以这种方式工作: http : //jsfiddle.net/gbb2ae4g/17/ The idea is to find expected end of page in a way similar to the previous version and then search for the last word ending with a dot and adjust number of words on page accordingly. 这个想法是用与先前版本相似的方式找到预期的页面结尾,然后搜索以结尾的最后一个单词,并相应地调整页面上的单词数。 This code assumes that dot is always followed by a space character unless it's the last character in the text. 这段代码假定点号后面总是空格字符,除非它是文本中的最后一个字符。

I've also updated the code given as the previous answer (first UPDATE), because it performed end of page check incorrectly. 我还更新了作为前一个答案给出的代码(第一次更新),因为它错误地执行了页尾检查。

If I understand you right, what you want is to cut number of words from a string 如果我理解正确,那么您想要的是减少字符串中的单词数

If it is, So read about the split method at MDN SPLIT METHOD . 如果是这样,请阅读MDN SPLIT METHOD中的split 方法

As you can see there, the split method have a limit parameter, so the next code will work: 如您所见,split方法具有一个limit参数,因此下一个代码将起作用:

var x = "bla bla bla bla bla";
var splits = x.split(" ",3);

Then splits will be an array that contain the values bla,bla,bla 然后splits将是一个包含值bla,bla,bla的数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM