What is the best way to divide a string into chunks of no more than 2000 characters each at the end of

Here is a brief excerpt from a string variable labeled results ...

2017-09-18  920.0100  922.0800  910.5999  915.0000  1294800
2017-09-15  924.6599  926.4899  916.3599  920.2899  2505400
2017-09-14  931.2500  932.7700  924.0000  925.1099  1397600
2017-09-13  930.6599  937.2500  929.8599  935.0900  1102600
2017-09-12  932.5900  933.4799  923.8610  932.0700  1134400
2017-09-11  934.2500  938.3800  926.9199  929.0800  1267000
2017-09-08  936.4899  936.9899  924.8800  926.5000  995100
2017-09-07  931.7299  936.4099  923.6199  935.9500  1212700

I am trying to break it into an array with each segment being around 2000 characters long and ending at the conclusion of a line. Currently, I am using the following code snippet but it splits each item in the array in the middle of a line.

var parts = results.match(/[\s\S]{1,2000}/g);

Answer №1

If you want to make sure that each match contains up to 2000 characters, you can utilize the following code:

let segments = matches.match(/[\s\S]{1,2000}$/gm);

Additional Information

  • [\s\S]{1,2000} - Any character between 1 and 2000 times, as many as possible,
  • $ - Indicates end of line
  • /gm - Enables matching multiple occurrences (g) and ensures $ matches end of a line(m).

Answer №2

Snippet of Code

View the code in action here

[\s\S]{1,200}(?:\v|$)

Explanation of Code

  • This regex will match any character between 1 and 200 times
  • It will then match either a vertical whitespace character \v or the end of the string/file $

If needed, adjust the range from 200 to 2000 depending on your specific requirements.

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

Customize hover effects in tailwind css with dynamic values

I am trying to customize the text color on hover based on different category names using tailwind CSS. In my configuration, I have assigned a specific color code for each category like this : tailwind.config.js theme: { extend: { } }, co ...

Formik's setField function is not properly updating the value of an array when using Material UI's autocomplete

When the data is retrieved from the API, it comes in the following format: otherLanguages:[{code:EN,name:"English"},{code:MD,name:"Mandarin"}] I am attempting to initialize the Autocomplete with this data: initialValues: { otherLa ...

How to enhance a class in JavaScript by adding a dynamic property

Within my code, I've defined a class which looks like this: class classA { id: number; name: string; constructor(data){ this.id = data?.id || 0; this.name = data?.name || ''; } } What I aim to do now is add ...

The response from Moment.js shows the date as "December 31, 1969."

Currently, I am in the process of recreating one of FCC's backend projects: Upon testing my code, I noticed that when I input the following URL: http://localhost:3000/1 The result is as follows: {"unix":"1","natural":"December 31, 1969"} var e ...

Utilizing the onclick event to call a function with multiple arguments within Template literals

How can I properly write a function with multiple arguments using JavaScript post ES6 template literals when called by an onclick event? Here is my code: function displayImg(imageUrl, gameName, gameSummary, gameYear, cardId) { cardId = cardId.toStrin ...

Another process is currently utilizing the file, preventing access by this process using StreamWriter

I encountered an issue where my text file, which is utilized to create and save my dictionary, is apparently being accessed by another process. I've tried using Process Explorer to identify what might be utilizing my file, but without any success. Bel ...

Retrieve the header tag from API using Nuxt

I am trying to dynamically set OG:Tags using an API head() { this.$axios .get(`............`) .then((response) => { this.og_title = response.data.message.course.course_name; this.og_description = response.data.message.course.description; ...

The JavaScript code is failing to retrieve any data from the API

import React, { Component } from 'react'; export class FetchData extends Component { static displayName = FetchData.name; constructor(props) { super(props); this.state = { users: [], loading: true }; } componentDidMount() { ...

Twilio Group MMS feature experiencing technical difficulties

I currently have a Twilio Trial account with an active number that supports SMS/MMS. My goal is to use this number for group MMS chats, but I am facing some challenges. After following a tutorial on Tut, I attempted to create a basic test using the provid ...

Encountering an Unresolved Runtime Issue: TypeError arises when attempting to access properties of undefined (specifically 'call') while utilizing the Image component in next.js

I'm currently experimenting with the Image component offered by next.js. This Is My Basic Header Component import Image from 'next/image' import React from 'react' import myImage from '../assets/IMG-20221115-WA0001.jpg' ...

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...

Error encountered: DOMException - Prevented a frame originating from "domain_name" from accessing a different origin frame

Utilizing the Mautic newsletter for my website has been a great experience. Here is the js code I've been using: /** This section should only be included once per page if manually copying **/ if (typeof MauticSDKLoaded == 'undefined') { ...

Ways to adjust the size or customize the appearance of a particular text in an option

I needed to adjust the font size of specific text within an option tag in my code snippet below. <select> <?php foreach($dataholder as $key=>$value): ?> <option value='<?php echo $value; ?>' ><?php echo ...

Ways to guarantee a distinct identifier for every object that derives from a prototype in JavaScript

My JavaScript constructor looks like this: var BaseThing = function() { this.id = generateGuid(); } When a new BaseThing is created, the ID is unique each time. var thingOne = new BaseThing(); var thingTwo = new BaseThing(); console.log(thingOne.id == ...

Error encountered: The function 'showErrorMessage' is not exported from the file '../helpers/alerts'

Within the directory ../helpers/alerts, there is a file called alerts.js const displaySuccessMessage = (success) => { <div className="alert alert-success">{success}</div> } const displayErrorMessage = (error) => { <di ...

What benefits does minifying server-side nodejs code provide?

Is there a benefit to minifying Node.js code in the same way as minifying JavaScript, particularly for reducing size and improving network download speed? When a file is required in Node.js, it is loaded into V8 and processed and stored in memory in some f ...

How come only the final element is being displayed from an array in JavaScript, rather than all of the elements present

I am facing an issue while attempting to extract specific information from a JSON data and create a new array with key-value pairs. However, instead of getting all the elements, it only returns the last one. Here is my current code snippet: const input = ...

ObservableResolve(): Unleashing the power of RxJS5 for handling asynchronous data streams

Hey there! To dive deeper into RxJS, I thought of creating my own custom Rx operator. So here's a straightforward one that seems to be working smoothly: Rx.Observable.prototype.multiply = function (input) { const source = this; return Rx.O ...

Moving icon that appears when hovering over a menu button

Before diving into this, please take a moment to visit the following website to understand my goal: You'll notice there is a noticeable RED arrow positioned below the menu. What I aim to accomplish is... when I hover over a menu button, the arrow smo ...

React Native's NativeBase checkbox component: Overlapping text causing the content to extend beyond the confines of the screen

I am having trouble getting the text inside a checkbox (using nativebase) to shrink. Does anyone know why this is happening? Do I need to add some flex properties? import React from "react" import {Box, Center, Checkbox, Heading, NativeBaseProv ...