Break down a string into an array containing a specific number of characters each

I'm currently working on a project that involves tweeting excerpts from a book daily via a small app.

The book's content is stored in a text file and I need to split it into 140-character-long strings for posting.

Initially, I tried using the split() function but didn't achieve the desired outcome.

There isn't a specific separator between the strings I want to create.

One approach I considered was counting the characters in the text file and setting a limit (number of splits) to generate 140 character strings, but I feel there might be a more straightforward method.

Any suggestions?

Below is my current code, utilizing test.txt to access the book content in text form.

var fs = require('fs');
var array = fs.readFileSync('./test.txt').toString().match("{1,140}");
for(i in array) {
    console.log(array[i]);
}

After implementing your advice, the console output seems unusual. Here's an updated version of my code:

var fs = require('fs');
var book = fs.readFileSync('./test.txt');
var lastSplit; // cache the position of the last split
var limit   = book.length > 140 ? 140 : book.length - lastSplit;
var urlsToAdd = book.slice(lastSplit, lastSplit + limit);
for(i in book) {
    console.log(book[i]);
}

Appreciate your help!

Answer №1

Instead of splitting the entire book into n splits, each consisting of 140 characters, you can optimize by remembering the position of the last split made.

var lastSplit; // cache the position of the last split
var limit = book.length - lastSplit > 140 ? 140 : book.length - lastSplit;
var urlsToAdd = book.slice(lastSplit, lastSplit + limit);
  • The lastSplit variable will store the position of the last split and also indicate how many characters have been tweeted so far.
  • Ensure to check the number of characters being tweeted to avoid exceeding the total length of the book.
  • You perform the split starting from the last known position by the desired character count, either lastSplit + 140 or up to the end of the book's length.

Keep in mind that this method is basic and may cut off words or sentences midway while tweeting.

Update: The code provided is a conceptual guide and may require modification based on your specific use case. However, you can try the following approach:

var fs = require('fs');
var book = fs.readFileSync('./test.txt');
var lastSplit = 0;

function tweet(book) {
var limit = book.length - lastSplit > 140 ? 140 : book.length - lastSplit;
var tweet = book.slice(lastSplit, lastSplit + limit);
lastSplit += limit;
return tweet;
}

while (lastSplit < book.length) {
 console.log(tweet(book));
}

Updated II: Functional Code Example with Dummy Data (to showcase the functionality)

function tweet(book) {
var lastSplit = 0;
while (lastSplit < book.length) {
var limit = book.length - lastSplit > 140 ? 140 : book.length - lastSplit;
var tweet = book.slice(lastSplit, lastSplit + limit);
lastSplit += limit;
$('body').append('<p>' + tweet + '</p>');
}
}

// Generating a dummy string with numbers from 0-800
tweet(Array.apply(null, {length: 800}).map(Number.call, Number).join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

Adding custom fields to the user model in MongoDB using Next Auth during login is not possible

When a user logs in via next auth, I am looking to include custom fields to the default user model. I followed the instructions provided in the official documentation at https://next-auth.js.org/tutorials/typeorm-custom-models. Here is the code snippet: ...

Differences between throwing errors, returning error objects, and using callbacks in Javascript

Currently, I am developing an assembler and simulator for a simplistic assembly language that my computer science students use during their classes. The project is being written in JavaScript with the intention of creating a user-friendly interface in the ...

What is the impact of updates to variable arrays on memory management in Swift, particularly in relation to Copy-on-Write (

I have been exploring ways to optimize my sorting algorithm for numbers in descending order. One particular function caught my attention, as it references the arr variable defined outside its scope (it's a nested function within another function). Th ...

Build error occurred due to the presence of the following error: Module parse failed with an unexpected character ''' (1:0)

I am facing an issue regarding an unexpected character in a node module file. Below is the content of my next.config.js file: /** * @type {import('next').NextConfig} */ const UglifyJsPlugin = require("uglifyjs-webpack-p ...

Execute function when button is clicked in ExpressJS

I am looking to execute a function on my node server when a button on my website is clicked: What I currently have: Index.html (I have not included the entire content for simplicity) <button id="tv">tv</button> Client.js (Client side) const ...

Issue with Three.js sample scene not functioning correctly

Forgive my lack of experience, but I am new to three.js and seeking guidance from the experts. I am starting with a basic scene to build my understanding from there. I began with an example scene from the documentation, but when I run it locally or on my s ...

Sorting JSON data using JQuery Ajax

I've encountered an issue with sorting JSON data. Here is the JSON data I'm working with: [ { nom: "TERRES LATINES", numero: "0473343687", image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12 ...

Explore various THREE.JS 3D models through a clickable link

I am struggling to make each object open a new page using a URL when clicked. No matter what I try, it doesn't seem to work properly. Can someone point out what I might be missing or doing wrong? Here is the click event code for the objects. If needed ...

Is there a way to get this reducer function to work within a TypeScript class?

For the first advent of code challenge this year, I decided to experiment with reducers. The following code worked perfectly: export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { const s ...

Updating the innerHTML of a button with a specific id using Javascript is not possible due to it being "null."

My objective is to create a button that, when clicked, triggers a function to alter the styling of the HTML tag as well as the text or innerHTML of the button itself. Sounds simple enough, right? Unfortunately... The HTML: <!DOCTYPE html> <html& ...

Combining hash arrays in Ruby

I'm currently working on combining multiple arrays of hashes in Ruby using a shared key. Here's an example to illustrate: country_info = [ {country_id: "US", country_desc: "United States"}, {country_id: "AU", country_desc: "Australia"} ] co ...

Executing multiple JQuery post requests simultaneously

I am currently working with three functions, each of which posts to a specific PHP page to retrieve data. However, since each PHP script requires some processing time, there is a delay in fetching the data. function nb1() { $.post("p1.php", { ...

Possible solution to address the issue: xhr.js:178 encountered a 403 error when attempting to access https://www.googleapis.com/youtube/v3/search?q=Tesla

Encountering this console error: xhr.js:178 GET https://www.googleapis.com/youtube/v3/search?q=river 403 A specific component was designed to utilize the API at a later point: const KEY = "mykeyas23d2sdffa12sasd12dfasdfasdfasdf"; export default ...

Switch from using jQuery to vanilla JavaScript for handling POST requests

I am looking to eliminate the jQuery dependency and use plain JavaScript instead in the code below for a post request. <script type="text/javascript> $(function() { $.post("test_post.php", { name: "John Doe", ...

Preserving variable scope in JavaScript even after defining a function

I am facing an issue with my JavaScript code that involves invoking a function within a function: var obj = { // returns the function with prevent default prepended. run: function(functor, context){ return function(e){ e.preventDefault(); ...

Suggestion for implementing numerous ajax countdown timers (one call per second)

I am currently developing a system with 100 countdown timers that each make an ajax call every second to retrieve the endTime from the database and update the countdown time. The reason for calling this every second is because the endTime can be altered. ...

If the value of the input matches, set the checkbox to be

I have successfully implemented functionality that allows the value of an input to be changed by clicking a checkbox. This works without any issues. Now, I am facing the challenge of automatically checking the checkbox when the page loads, but only if the ...

Exploding a key value pair and grouping matching key values into one key - here's how to do it!

I have encountered a practical issue recently while working on ajax form submission. There are checkboxes involved and I need all checkboxes with the same name to be stored as key value pairs. For example, if there are 4 checkboxes with the name attribute ...