Confirming that a lengthy string contains a sufficient number of breakable spaces for proper presentation

When facing the challenge of printing table content with unruly strings that lacked spaces for proper word wrapping, I encountered difficulties in maintaining consistent formatting. This led me to seek a solution for validating user input before reaching the print stage, as I wanted to avoid using CSS techniques that may not be fully supported by the print engine.

To address the issue of limiting contiguous characters in the text, I devised a method outlined below. While effective, I am still unsure if this is the best approach:

const limit = 25; // arbitrary threshold

/* text block possibly unformatted 
without spaces for table alignment */
let str = some_user_input;

/* split text into array values using 
any whitespace (added 'g' for safety) */

if(str.length){
 let spaced = str.split(/\s+/g);

 //verify array existence

 if(spaced.length){
  //check each array item for contiguous character limit
  for(let i = 0; i < spaced.length; i++){
    if(spaced[i].length > limit){
      return false;
    }
  }//endLoop
 }
 else{
    if(str.length > limit) return false;
 }
}
return true;

Answer №1

When working with regular expressions, a simple approach would be to use one to verify if there are consecutive characters without any whitespace in a given string. Below is an example:

const limit = 4;
const reLimit = new RegExp(`\\S{${limit},}`);

const validate = (str) => !reLimit.test(str);

console.log(validate("foo bar")) // true
console.log(validate("foo barz")) // false

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

When passing req.body to another file for processing, it is displaying as undefined in node.js

Currently tackling an issue with a project involving nodejs where the request body is showing up as undefined Fetching some data on the client side, but encountering difficulties Received an error pointing out that the property is either undefined or nul ...

Sending a unicode PHP variable to JavaScript is a breeze

I am attempting to transfer the titles and excerpts of Persian Wordpress posts to JavaScript. Below is the code in a .php script file: function change(){ document.getElementById("link").innerHTML = '<a href="$links[2]">$titles[2]< ...

Encountered an error saying 'TextEncoder is not defined' when running Jest in Next.js version 14

I am currently working on testing some API call methods using Jest in a Next.js 14 environment. Below is my jest.config.js file: const nextJest = require("next/jest"); /** @type {import('jest').Config} */ const createJestConfig = next ...

Connect the AngularJS data model with a Foundation checkbox element

I am attempting to link a model (a boolean value) to a checkbox created with Foundation (Zurb). I have created a small demonstration displaying the issue: http://jsfiddle.net/JmZes/53/ One approach could involve simply creating a function that triggers o ...

Differences between React's useCallback and useMemo when handling JSX components

I have created a custom component called CardList: function CardList({ data = [], isLoading = false, ListHeaderComponent, ListEmptyComponent, ...props }) { const keyExtractor = useCallback(({ id }) => id, []); const renderItem = useCallba ...

When an if statement is triggered by an overload of information, it initiates the start of a fresh

I am in need of creating an if statement that will trigger whenever images with IDs 0 to 3 (a total of 4 images) are loaded. This if statement should then generate a new row containing 0 to 3 images, and the same logic needs to be applied for words as well ...

Res.redirect() showing unexpected behavior

In my current setup, I am utilizing a modified version of the vhost connect/express middleware. Within this middleware, there is a check for the presence of the www subdomain. If the subdomain is found, it should redirect to the host + path without the www ...

Using arrays to categorize sub-classes

I am facing an issue with a JSON string that contains a list of arrays. I need to assign the array to a different class. Below is my JSON data: { "timestamp" : "1390257561" , "bids" : [ [ "833.98" , "3.14189766" ] , [ "833.73" , ...

What is the best way to call an API within a loop using Node.js?

How can I efficiently make API calls based on page numbers in a loop? I am using the request() function for API calling, but when debugging my code, the response block is not reached and I do not get a response. Can someone please provide guidance on how ...

Angular 9: Trouble encountered with utilizing custom error handler for error instances

I'm currently working on implementing a custom error handling system in Angular using the ErrorHandler class. This is what my Globalerror service looks like: export class CustomErrors extends Error { button?: any; errObject: any; constructor() ...

ES6 does not allow the use of native setters when extending the HTMLButtonElement

Looking for a way to utilize the native setters and getters for an extended HTMLButtonElement, particularly focusing on the 'disabled' property. You can find more information about the property here: https://developer.mozilla.org/en-US/docs/Web/ ...

I am looking to create a password generator that saves all generated options to a file

I am looking to create a custom password generator that writes all generated options to a file. For example, using the numbers "0123456789" and having a password length of 3 characters. However, I am facing an issue with the file writing process where it ...

Displaying imported JSON data in a tabular format

I am struggling with writing a function in my VueJS template that sends a request to the backend API with a specific key and then displays the JSON response in a table. For example, here is a sample of the JSON data: {"driver_id":1,"driver_name":"{driver ...

Please provide an explanation of how babel and node.js are interconnected within the ReactJS framework

As a beginner in ReactJS, I'm curious about the role of Node.js in the React ecosystem. Can someone please explain its importance to me? ...

I am interested in extracting specific data from the JSON response

I am trying to extract the value of the message parameter under the messages array where the parameter name is equal to documentId (highlighted in bold below). However, the code I have tried so far does not achieve this as needed. dynamic obj = JsonConver ...

Retrieving and implementing values from specified Object keys

I'm working with an array that looks like this: var Brand = { "Brand1-Parameter1-SubBrand1": [{ "Image": "animal", "Heading": "SubBrand1", "Link": "SubBrand1" }], & ...

Tips for showing JSON data within multiple <div> elements on an HTML page with AngularJS and ng-repeat

I am looking to display JSON values on my HTML page, each in a separate div based on the image URL value from the .json file. However, I am encountering difficulties in displaying these values in the divs. Can someone please guide me on how to iterate and ...

Making sure to detect page refresh or closure using jQuery or JavaScript

Could there be a way to determine if a page has been refreshed or closed using jQuery or javascript? The current scenario involves having certain database values that need to be deleted if the user either refreshes or leaves the page. AJAX calls are bein ...

Steps for updating object state in React

Here is the code snippet that I am working with: this.state = { user: null } I am trying to figure out how to set the name property of the user when it exists. Unfortunately, using this syntax this.setState({user.name: 'Bob') doesn't ...

Is there a way to merge these arrays into a single array?

With the current code I am obtaining numerous JSON objects within separate arrays: Here is the code snippet: for (let i=1; i<=150;i++){ fetch(`A valid URL ${i}`) .then(result => result.json()) .then(result => console.log(result.data.results)) ...