Hello amazing Stack community,
I am currently striving to create a straightforward JavaScript function that can accurately count the total number of words from a given string value.
Furthermore, I aim to store a specific number, X, of words into an array in order to loop through them with additional HTML elements surrounding each word.
For example, let's consider the following 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.
Below is the snippet of code I am currently working on:
// Variables for Maximum Words
var wordsMaxFirstPage = 40;
var wordsMaxOthersPages = 50;
// Default field (Example String)
var defaultField = $(this).find('.c_6937 .textarea .value');
// Count the number of words in this form
var countLengthOfCommentPage = defaultField.text().split(' ').length;
// Create an array of comments split by the 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 generate 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 part that confuses me is when I am constructing the array. I am aware that I am using the substring method which operates with characters.
So, here's my question – is there a simpler way to build the array using a regex function or am I overlooking a straightforward solution?