Tips for segmenting text into pages according to the dimensions of the viewport and the font style

Here's a puzzle for you. I have a horizontal slider that loads pages via Ajax, with pre-loading features to maintain smooth performance. Similar to Facebook Billboarding but with a slight twist. By determining the viewport size, I calculate boxSizeX and boxSizeY.

The server sends a block of text containing X words. The text is displayed using a monospaced font with a 13px font size and a line-height of 1em (also 13px). My challenge now is to break down the text into chunks that fit perfectly within boxSizeX and boxSizeY without cutting words in half or splitting sentences before the last two words. Any suggestions on potential obstacles to watch out for would be greatly appreciated as I want to cover all bases.

All this computation is done in JavaScript, though the initial call for text can include serving boxSize values to the server for heavy processing. How would you approach this task? I'm not certain about everything I need to consider such as browser rendering, font issues, and more. Thank you for any insights!

Answer №1

If I have grasped the essence of your inquiry correctly, the initial step for a monospaced font would involve splitting the string into two equal parts and examining for any broken words—is that accurate?

Below is a fundamental method for dividing a string in half, adding split words to the first part, removing them from the second part, eliminating any leading spaces from the latter portion of the split string, and presenting the outcome in two distinct strings:

let str = "Works like Facebook Billboarding, if anyone remembers the FB hacker cup, yet slightly different. So I compute the size of the block based on the viewport and I get boxSizeX and boxSizeY.";
let halfway = Math.round(str.length/2);
let first_half = str.slice(0, halfway);
let second_half = str.slice(halfway);
let broken_word = second_half.indexOf(" ");
let orphan = (second_half.slice(0, broken_word));
first_half = first_half.concat(orphan);
second_half = second_half.slice(broken_word).trim()
console.log(first_half + " --halfway split here-- " + second_half)

In cases where either the end of first_half or the beginning of second_half contains a space, indicating the absence of a broken word, you should execute the broken_word function solely within that condition.

By investing a bit more effort, you can extract the last two words preceding the final period in the first part of the string using a regex by reversing the string:

const backwards = first_half.split("").reverse().join("");
z = (backwards.match(/(\.\S+\s\S+)/)[0]);
end_sentence = z.split("").reverse().join("");
console.log(end_sentence);

Subsequently, you could leverage backwards.indexOf(".") or split first_half after the conclusion of end_sentence, then utilize slice and concat operations to obtain the desired result for the initial segment of the string.

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

Find a partial match in the regular expression

I am currently working on filtering a list of names using regular expressions (regex). The data is stored in the following format: [ { "firstName": "Jhon", "lastName": "Doe", }, ... ] Users have the option t ...

The occurrences of Swiper events fail to be activated

I am in the process of developing a gallery website that utilizes the Swiper JQuery plugin for slideshows and isotope for grid layout. Each individual item within the gallery has its own slider and corresponding isotope element. The Swiper gallery is in ...

Error encountered while trying to eliminate array element

I have a project in the works that involves creating a page where users can filter suggestions and vote for their favorites. The screen is divided into 3 tabs: [Top Rated], [Newest], and [My Votes]. Upon loading the screen, a call to the database is made ...

Fastify endpoint failing to respond to designated URL

Within my code, there is a router setup: fastify.get('/:link', (req, reply) => { req.params.url = req.host+req.url; reply.view("template.ejs",req.params); }); I am trying to capture URLs and process them in the template. All URLs are ...

Is it Possible to Stack Multiple Rows of Images with HTML5/CSS3?

I am struggling to arrange images in rows, but I'm facing unexpected outcomes. The images only break to a new line when the page is filled. I attempted to use overflow:hidden, however, the expanding images end up hidden under white space. I can't ...

Is it possible to create a progress bar in AngularJS that features several different

Seeking recommendations: I am in need of displaying a bar with three statuses using different colors all within the same bar. Any ideas? ...

What steps do I need to take to integrate my RASA assistant into my personal website?

Deploying my rasa chatbot on my live website is my next step. While Rasa worked smoothly on my localhost server, as a newcomer to web development, I found the official guide provided by RASA in the link below a bit challenging to comprehend: The RASA guid ...

The .hide method is failing to execute within a click event handler

In my current code snippet, I have the following: $(document).ready(function() { $('.search a').click(function() { $('.search2').show(); }); $('.search-close').click(function() { $('.search2').hide() ...

Obtain the value of a checkbox using jQuery

Here is an example of dynamic checkboxes: <input type="checkbox" checked="checked" value="1" name="user_mail_check[]" class="ami"> <input type="checkbox" checked="checked" value="2" name="user_mail_check[]" class="ami"> <input type="checkbo ...

Locate element in Cypress with ID that includes a span element

Recently diving into Cypress, I'm looking to locate an element with a dynamic id that contains specific text. For instance: ... <div class="col2"> <button id="random-city-name_type-125" class="btn-secondary"> ...

What is the most effective method of verifying image loading?

Currently, I am utilizing the mjpeg format to display a stream from an IP camera. However, I have been experiencing issues with the stability of the stream. The problem lies in not knowing when exactly the stream begins and, therefore, requiring a check on ...

Using TypeScript to type styled-system props

Currently, I am utilizing styled-system and one of the main features of this library is its shorthand props that allow for simple and quick theming. Although I have streamlined my component, a significant aspect lies here: import React from 'react&a ...

Retrieving particular excerpts from a block of text that includes the keyword "javascript."

I have a chunk of string containing HTML source code. Currently, I am trying to read specific tags that I need using JavaScript. Since I am new to programming, I'm unsure how to proceed. Can anyone assist me with this? The issue lies in the following ...

Is there a way to view the text as I enter it while drawing text on an image canvas?

I currently have a canvas setup that allows users to upload an image and display it on the canvas. Users can then input text to be drawn on the image by clicking the submit button. However, I would like the entered text to appear on the image as it is bein ...

Reproducing scripts in Google Tag Manager and React/Next applications

Currently, I am delving into the realm of Google Tag Manager and React + Next.js for the first time. This experience is proving to be quite intriguing as my familiarity with GTM is limited and my exposure to React is even less. Nonetheless, it's not a ...

Check if any element from the first array exists in any nested array of the second array and return a Boolean

Having two distinct types of arrays, firstArrayObject = [{name: "sample", number: 23}, {name: "sample2", number: 25}]. The second object takes the form of secondObject = {someAttribute: bla, numbers: [23, 26, 27, 28} My goal is to det ...

Issues with Stylesheet Rendering in Firefox

Take a look at this Kendo UI Dojo example: https://i.sstatic.net/lVfNM.png When rendered in Firefox, the "right" should also be placed in the header, but it's not. It works correctly in IE11 and Chrome. What am I doing wrong? ...

What causes my animation to “reset” upon adding a new element using innerHTML?

One of the functionalities on my webpage involves a script that inserts a div called "doge" using innerHTML when a button is clicked. Additionally, there is a CSS keyframes animation applied to another div on the same page. However, whenever the button is ...

Using Angular 4: Redirecting Menu to Component with Electron

I am currently working on my first project using Angular 4 and Electron to develop a desktop application. One of the challenges I'm facing is figuring out how to redirect to a specific component when a submenu item is clicked after overriding the ele ...

References to high order functions in JavaScript

Although the code below is functional, I believe there might be a more efficient approach. I am currently passing a reference to the higher-order function's scope. var self=this; this.nodeModal.find(".modal-footer .save").click(function(){ ...