Instructions for separating a string into smaller parts, further splitting one of the resulting parts along with another associated value, and then combining the leftover segments with the remaining parts

My goal is to work with a string that is between 2000 and 3000 characters long, containing over a hundred non-uniformly placed \n characters. I want to divide this string into segments of 1000 characters each. In the resulting array of strings, I want to ensure that each segment ends at the last occurrence of \n (remaining intact if no \n is present). Any leftover characters after the last \n should be added to the beginning of the next segment in the array. This process should happen sequentially for each segment after it has been processed up to the last \n.

I hope my explanation is clear. Here is the code snippet:

module.exports={
    async split(text,length,max){
        if (text.length > max){
            return;
        }
        let regex = new RegExp(`.{1,${length}}`, "g");
        let splitted = text.match(regex);
        return splitted;
    }
}

The following section shows how the function is utilized:

        let splitted = await split(lyrics,1000,6000)

Although I have successfully split the text every 1000 characters, I am struggling with implementing the functionality described above. Can someone provide assistance?

EDIT: Let's consider an example where we want to split the string into segments of maximum 20 characters, ensuring the total length does not exceed 1000 characters. If the limit is surpassed, nothing will be returned. The secondary splitting operation (as explained in the initial question using \n) can also use whitespace ( ).

For instance, given the string:

Hello, I love Stack Overflow, and it is super cool

let string = `Hello, I love Stack Overflow, and it is super cool`
let splitted = await split(string, 10, 1000)

We currently get:

["Hello, I l", "ove Stack ", "Overflow, ", "and it is ", "super cool"]

If we were to introduce another argument in the split() function:

async split(text, length, max, splitAt)

Where splitAt can represent either \n or , based on preference.

The desired output would be:

["Hello, I", "love Stack", "Overflow,", "and it is", "super cool"]

I am having trouble figuring out how to achieve this result.

Answer №1

There is no need for this method to be declared as async. Simply iterate through the string, split it by a certain length, and use the lastIndexOf function to find the position of the specified character for splitting. Then, extract that chunk into an array with the help of substring

One possible implementation could look like this:

function customSplit(text, len, max, splitAt) {
  if (text.length > max) {
    return;
  }

  let pos = 0;
  const chunks = []
  while (pos < text.length) {
    if (pos + len >= text.length) {
      chunks.push(text.substring(pos));
      pos = text.length
    } else {
      const separatorPosition = text.substring(pos, pos + len + 1).lastIndexOf(splitAt);
      chunks.push(text.substring(pos, pos + separatorPosition));
      pos += separatorPosition + 1;
    }
  }
  return chunks;

}

let inputString = `Hello, I love Stack Overflow, and it is super cool`
let result = customSplit(inputString, 10, 1000, " ")
console.log(result);

Answer №2

My interpretation is that you are looking to divide the text into segments of no more than 1000 characters each, with each segment ending in a newline character.

function splitText(str, chunkSize){
    const chunks = [];
    let currentChunk = "";
    str.split("\n").forEach(part => {
        if(currentChunk.length + part.length > chunkSize){
            // Add the completed chunk to the array and reset current chunk.
            chunks.push(currentChunk);
            currentChunk = "";
        }
        // Append newline character to parts if current chunk is not empty.
        currentChunk.length 
           ? currentChunk += `\n${part}`
           : currentChunk += part
    })
    
    // Include the final chunk if it's not empty.
    if(currentChunk.length) chunks.push(currentChunk);
    
    return chunks;
}

This function should split the text as desired, but I haven't tested it yet as I wrote it using my phone.

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

Obtaining a string from the String prototype can be achieved by using

My goal is to create a custom log method for the String object that will print out the actual string value, but I'm facing some difficulties in getting it to work correctly. String.prototype.log = function() { console.log(this.valueOf()); } &apos ...

NextJS allows for custom styling of Tiktok embeds to create a unique and

Currently, I am in the process of constructing a website that integrates Tiktok oEmbed functionality. Thus far, everything is running smoothly, but I have encountered an issue - how can I customize the styling to make the body background transparent? I ha ...

The aspect ratio of an image is being calculated by loading the image twice

I am currently facing the issue where the same image is loading twice for a single preview. The first time the image is loaded for preview purposes in an iframe. The second time, the image metadata such as width and height are fetched with the same path. ...

Error 500: An invalid data type was encountered in an express.js node.js environment

Currently, I am in the process of developing an Authentication page using a combination of node.js, express.js, and mysql2. The user ID and password entered on the webpage are then passed through app.post('/login',...). However, upon submitting t ...

JavaScript: A pair of radio button selections

I'm facing an issue with a short form that has two questions and radio buttons for answers. When the first question is answered "No," I used JS code to disable options for the second question, which works fine. However, if the answer is changed back t ...

React: Trying to use the map function on an empty array will result in an error

I am currently facing an issue while trying to populate a shopping cart with items. Even though I have initialized the cart as an empty array, I keep encountering the following error: TypeError: cart.map is not a function ProductContext.js:34 addItemToCar ...

Incorporating additional options onto the menu

I recently designed a menu on https://codepen.io/ettrics/pen/ZYqKGb with 5 unique menu titles. However, I now have the need to add a sixth title to the menu. After attempting to do so by adding "strip6" in my CSS, the menu ended up malfunctioning and looki ...

Adjust the viewport width based on the width of the device

Having difficulty adjusting the meta tag viewport content width based on device width, I am struggling to achieve my desired outcome. Here is the code snippet I have been working with: Code snippet: <meta id="viewport" name="viewport" content="width=d ...

Pressing the reset button will initiate once the loader has finished

Hello everyone, I'm currently working on creating a button that transforms into a loader when submitted and then reverts back to a button after the form is successfully submitted. I suspect the issue lies within my JavaScript. I'm not sure how ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

Unable to transmit props through components with Vue router

Hey there, I'm currently facing an issue with passing props from my vue router. It seems like nothing is being printed and when I checked in the mounted hook, it's returning undefined. However, strangely enough, when I use console.log(this.$route ...

Ways to determine if an element has exceeded its container's boundaries

After creating the codesandbox, I have developed a webapp that heavily relies on user input. To keep it simple for demonstration purposes, I am displaying various authors on an A4 formatted page using `page` and `font-size` with the `vw` unit for responsiv ...

Use jQuery to switch back and forth between the login and registration forms on a single

I've set up two forms, one for login and one for registration, with the default view showing the login form. There's a link that says "Don't have an account?" and when it's clicked, the registration form will display while the login for ...

Calling Number() on a string will result in returning a value of NaN

Currently, I am working on the following code snippet: app.put("/transaction/:value/:id1/:id2", async(req,res) => { try { const {value,id1,id2} = req.params; const bal1 = await pool.query("Select balance from balance where id=$1",[i ...

What is the best way to parse this JSON data?

Here is a string that I have: [{"data1":"A"},{"data2":"B"},{"data3":"C"}] Using jQuery, I converted this string to JSON: test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]'); After conversion, I obtained 3 objects: https:/ ...

Fixing Firebase and React errors in JavaScript functions

Thank you for your understanding. I am currently integrating Firebase into my website. However, when I invoke the signup function in FormUp.js (which is declared in AuthContext.js), it does not reference the function definition. As a result, the function c ...

When clicking to open the md-select on Angular Material 1.1.0, an unwanted [object object] is being appended

Every time I try to open the md-select input, an [object Object] (string) is added to the body tag. Click here to see the md-select input After clicking the md-select once, this is how the body looks ...

Design a button in d3.js that toggles the visibility of a rectangle and text

Looking to use d3.js to create a simple list from data in a box, complete with a button to toggle the visibility of the box and its content. Ran into two errors during implementation: 1) The list is starting at item 2 for some reason - where's the fi ...

Emulate clicking a radio button (using PHP and JS)

For the past week, I've been struggling to solve this issue with no luck. I admit that I am new to this area, so I ask for your patience. My current problem involves using TastyIgniter, an online food ordering system. In order to add items to the car ...

Is there a way to restrict access to my website to only be opened in the Chrome browser?

Is there a way to prevent my web application from loading when the link is opened in browsers other than Chrome? Can this be achieved using Javascript or Java? I want to restrict the usage of my web application to only Chrome. Any assistance would be appre ...