简体   繁体   中英

Create an array of X number of words from javascript String

Hello Stack community,

I am trying to acheive a simple javascript function to first count the total number of words from a given string value.

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.

For exemple, I have this 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.

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

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.

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. 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/ . 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 .

As you can see there, the split method have a limit parameter, so the next code will work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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