Form a collection of X amount of words using a string in JavaScript

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?

Answer №1

It appears that you are already creating an array, but not saving it properly ;).

Using the `split()` function in Javascript allows you to split a given string and create an array with the resulting pieces.

Here is a better way to handle the array creation:

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

If you are facing any issues, please let me know if this solution works for you.

UPDATE

Upon further inspection, it seems that my initial suggestion would result in having only one word in each element of the `chunks` array, which is not suitable for your situation.

The problem with your original code lies in the loop not taking into account the lengths of each word in the array.

Here is an updated approach to building the array:

var words = defaultField.text().split(' ');
var totalWordsCount = words.length;
var wordsCountPerPage = 10;
var chunks = [];

for (var i = 0; i < totalWordsCount; i+=wordsCountPerPage) {
    chunks.push(words.slice(i, Math.min(i+wordsCountPerPage, totalWordsCount)).join(' '));
}

I have made adjustments in the code and tested it in the jsFiddle provided. Please let me know if this resolves the issue.

UPDATE II

In response to your request in the comments, I have updated the code in the jsFiddle to detect the end of the last sentence before reaching the word limit per page in order to display full sentences whenever possible. You can check out the updated version here: http://jsfiddle.net/gbb2ae4g/17/. The code now considers the presence of a period and adjusts the number of words on the page accordingly.

I have also corrected the end of page check in the previous version of the code. Thank you for bringing that to my attention.

Answer №2

To summarize your request, you are looking to reduce the number of words in a given string

If this is the case, I recommend exploring the split method on the following link: MDN SPLIT METHOD.

By utilizing the limit parameter within the split method as demonstrated in the code snippet below:

var sampleString = "foo foo foo foo foo";
var wordArray = sampleString.split(" ", 3);

The resulting wordArray will store the values foo,foo,foo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Switching a div's visibility when a link is clicked

http://jsfiddle.net/FsCHJ/2/ Currently, when I add another link, it automatically uses the same functionality as the toggle button. What I want is for "Toggle Edit Mode" to toggle a hidden div on and off. I attempted to modify the code from $("a").click(f ...

Converting an Angular1 App into a VueJs app: A step-by-step guide

Let's dive right in: I'm embarking on the journey of revamping an app that originally utilized Angular 1, but this time around I'll be harnessing the power of VueJS 2. As someone unfamiliar with Angular 1, I'm faced with some perplexing ...

issue with data binding in ons-dialog

Utilizing an ons-dialog to display a popup prompting the user to sign up for a newsletter. I have set a 3-second timeout to prevent users from immediately closing the prompt without reading it or waiting. I aim to initially show the dialog with the ' ...

"Embed" three.js within SmartMS

Is it possible to incorporate this simple three.js example into Smart Mobile Studio without extensive wrapping? I attempted to copy the window.onload content into an asm section but was unsuccessful. <!DOCTYPE html> <html> <head> <t ...

Begin with the constant element within the array initialization

What is the reason for the compiler (VC++) disallowing (error C2975) const int HASH[] = {24593, 49157}; bitset<HASH[0]> k; and how can I resolve this issue (initializing templates with constant values from an array)? ...

Exploring the capabilities of data processing in Node.js

I've been attempting to read data from a locally stored JSON file, organize it into individual JS objects, and add them to a queue. However, I'm struggling to find a way to test my parsing function to ensure it's functioning correctly. My cu ...

What is the best way to find information in a multi-page table?

I've implemented a table with pagination and search functionality to look up data within the table. However, currently the search only works within the current page of the table rather than searching the entire dataset. Is there a way to modify the se ...

Even with React.memo(), functional components continue to trigger re-renders

I am facing an issue with my button component that contains a button inside it. The button has a state isActive and a click function passed to it. Upon clicking the button, the isActive flag changes, triggering the app to fetch data accordingly. However, t ...

Establish a connection to a regular socket by utilizing WebSocket technology

I am attempting to connect a client interface to a hardware device using WebSocket in a browser like Chrome. The code snippet I have been using for connection is as follows: var ws = new WebSocket("ws://127.0.0.1:13854"); ws.onopen = function() ... Howev ...

Mistakenly appearing at the top of the window instead of the bottom of the window

Utilizing Vue.js to fetch resources from a Laravel API periodically and paginate(), after retrieving the initial 10 instances, I aim to get the next 10. Here's how my method looks: scroll () { window.onscroll = () => { let bottomOf ...

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

Don't forget to keep track of when the user has closed

How can I ensure that the cache retains the user's action of closing the div? Currently, when I close the div and refresh the page, it reverts back to its original state. Is there a way to make this change persistent? Experience it live: Here is the ...

Tips for surviving a server restart while using sequelize with a postgres database and handling migrations

Within my express application, I utilize Sequelize for database management. Below is the bootstrap code that I use: db.sequelize .sync({ force: true}) .complete(function(err) { if (err) { throw err[0]; } else { //seed requi ...

What is the process of updating values in an object that is part of an array?

I am currently facing an issue where I am attempting to implement an edit function to replace text and dates. While I have managed to successfully update the text using the DOM, the edited values revert back to their original form upon page refresh. I susp ...

jQuery - delete a single word that is case-sensitive

Is there a way to eliminate a specific case-sensitive word from a fully loaded webpage? The word in question is "Posts" and it appears within a div called #pd_top_rated_holder that is generated by Javascript. The Javascript code is sourced externally, so ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Issue with the dynamic updating of props

Every time a radio button is clicked within Test.js, the handleclick function executes, updating an array. However, the issue lies in not sending this updated array back to graph_test.js. As a result, graph_test.js only receives the initial array filled wi ...

Issue with triggering ReactJS onClick function accurately

For the function to work correctly, I had to add e.preventDefault(). However, my goal is for it to redirect the user to '/' after submitting the form. Below is the function that I am attempting to trigger: onAddPoints = (e) => { e.prevent ...

Honing in on JavaScript Media Queries within React

I have been attempting to incorporate the media query concept from a resource I found here in my React project. However, when testing the code snippet below, I encountered the following error: TypeError: isMobile.addListener is not a function function App ...