Pattern for identifying text that exclusively consists of whitespace characters and `<br>` tags

Here is an example of a string:

                       <br />                     <br />                <br />

Sometimes the string can look like this:

            <br />          <br />

Or simply like this:

            <br />

How can I determine if a string contains only whitespace and br tags using JavaScript? For example: if(/\s*/.test(content)){ }

Answer №1

When checking for whitespace and <br />, you should use an alternation with zero or more repeats, anchored at the start and end:

if(/^(?:\s|<br \/>)*$/.test(content)){ }

This breakdown is as follows:

  • ^ - indicates the start of input
  • (?:...) - a non-capturing group
  • \s - represents any single whitespace character
  • | - signifies an alternation between two options
  • <br \/> - matches the literal string <br /> (escaping the /)
  • * - allows for zero or multiple occurrences of the preceding group
  • $ - marks the end of input

If there is a possibility that the space or solidus within the tag may be missing, or the space may be repeated, you can modify the regex to:

if(/^(?:\s|<br *\/?>)*$/.test(content)){ }

Adding * after the space allows for zero or multiple spaces; adding ? after the solidus (/) makes it optional.

Please note: The above patterns do not account for attributes on the br tag, such as <br class="foo" />, <br data-foo="bar"/>, etc. Additionally, they match empty strings.

To include attributes while still matching empty strings:

if(/^(?:\s|<br[^>]*>)*$/.test(content)){ }
// Change ----^^^^

To consider attributes and require at least one whitespace or br tag (eliminating empty strings):

if(/^(?:\s|<br[^>]*>)+$/.test(content)){ }
// Change ------- ---^

Answer №2

Consider this sample string:

let text = "    <br />   ";

My first step would be to eliminate all whitespace from the input, avoiding the need for the regex to account for it:

let modifiedText = text.replace(/\s/g, '');
//after this modification, modifiedText will only contain "<br/>"

Next, you can use a regex to verify if <br/> is present in the modified text:

let pattern = /^(?:<br\/>)*$/;
let isValid = pattern.test(modifiedText);

Check out a live demo here

Answer №3

"^\s*<br />$"

This code snippet will select all lines that have any amount of whitespace characters at the beginning and end with "
"

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

Utilize JavaScript to trigger a div pop-up directly beneath the input field

Here is the input box code: <input type='text' size='2' name='action_qty' onmouseup='showHideChangePopUp()'> Along with the pop-up div code: <div id='div_change_qty' name='div_change_qty&ap ...

Loading content dynamically into a div from an external or internal source can greatly enhance user experience on a website. By

As I work on my website, I am incorporating a div structure as shown below: <div class="container"> <div class="one-third column"> <a id="tab1" href="inc/tab1.html"><h2>tab1</h2></a> </div> & ...

Improving the efficiency of rendering multiple objects on a canvas

I'm currently working on developing a simulation for ants using the basic Javascript canvas renderer. Here is a snippet of the rendering code: render(simulation) { let ctx = this.ctx; // Clearing previous frame ctx.clearRect(0, ...

Embracing async-await while awaiting events in node.js

I am attempting to incorporate async await into a project that is event-driven, but encountering an error. The specific error message I am receiving is: tmpFile = await readFileAsync('tmp.png'); ^^^^^^^^^^^^^ SyntaxError: Unexpec ...

Validation within nested Joi schemas

Need help validating a nested object conditionally based on a parent value. const schema = Joi.object({ a: Joi.string(), b: Joi.object({ c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Jo ...

Node.js Project Using a Specific URL and Parameter

Two things are on my mind: 1. I'm trying to set up my project's URL as 127.0.0.1:8080/param=id, but I've been unsuccessful so far despite attempting the following: app.get('/param=id', function(req, res) { console.log(req.param ...

Checking for null properties in Typescript objectsorHow to verify if a

What is a simple way to determine if the properties of an object in TypeScript are nullable? For example export default interface UserDto{ ID?:int; USER_NAME?:string; FIRST_NAME?:string; LAST_NAME?:string; USER_ROLE?: ...

Forward after asynchronous JavaScript and XML (AJAX)

Currently, I am working on an MVC project where I need to achieve the following: The scenario involves sending an ajax request from a JS script and then redirecting to a page along with a model once the request is processed. I attempted to send a form as ...

Building a hierarchical object structure from an array

I am working with an array of objects that looks like this: const sorted = [ { IsoCode: "EUR", Buy: 1.948, Sell: 1.963 }, { IsoCode: "GBP", Buy: 2.1184, Sell: 2.1894 }, { IsoCode: "USD", Buy: 1.5781, Sell: 1.6484 }, ] and my ...

Is it possible to adjust the CSS code linked to the HTML tag based on the specific webpage being viewed?

I am facing an issue with the homepage of my website, which uses Scrollmagic.js for smooth scrolling. In order for the sticky footer CSS to work properly on all other pages, the HTML tag needs to have a height of 100%. However, if I add this height value t ...

Having difficulty configuring unique paths for multiple APIs using Socket.IO, ExpressJS, and Nginx

I am currently working on setting up multiple APIs on a single VPS and serving them through Nginx. My goal is to have all of them organized in separate sub-locations, as shown in the example below: For Express remote paths: [myhost].com/apps/app1/api [myh ...

Manipulating a 2D array in Javascript and Jquery: Implementing push functionality

I am trying to set up an array structure as follows: track[divID][wrapID] However, when I attempted track[divID][wrapID] = wrapID, I encountered an issue. This is because I need to add more elements to the second dimension in another loop, like this: tr ...

What is the proper method for delivering Javascript code with rendered HTTP to a client?

During the development process, I made a decision to switch to server-side rendering in order to have better control and take advantage of other benefits. My web application relies heavily on AJAX with no url redirecting, creating a website that dynamicall ...

Is it feasible to set a default value in an HTML input field that is not editable using JavaScript?

Is there a way to set a default value in an input field of HTML that is not editable, and then allow users to add additional text to it? For example, having 'AB' as the default and uneditable starting characters, followed by any numbers such as A ...

Following the execution of an AJAX request, the jquery script fails to run

I've encountered an issue with my website that utilizes pagination, filtering with jQuery and AJAX. Everything was functioning smoothly until I decided to switch my links to JavaScript links. When on the homepage without any filtering or pagination a ...

Retrieve the content following a successful loading of the remote URL

I have been utilizing this function to retrieve content from a Remote URL function fetchContent($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $scrapedPage = curl_exec($ch); curl_close($ch); $content = $scrapedPage; return ...

`Failure to prompt an error following an unsuccessful post request in a node.js application using axios and express`

I'm currently facing an issue while trying to implement password change validation. The problem lies in not receiving the errorMessage from the server in case of an error. Although I've successfully managed to update the password and send back a ...

Ensure that all form fields are completed and accurate before the Stripe payment modal is displayed

I've encountered an issue where the stripe payment modal appears before my form validation is complete. I am using the jQuery validation plugin for this purpose. I attempted to integrate the Stripe code within the submitHandler function, but it did no ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

What is the process for executing Selenium IDE scripts in Selenium RC?

As a newcomer to using the selenium testing tool, I am seeking guidance on running selenium IDE scripts within selenium RC. I would greatly appreciate examples and screenshots to help me better understand the process. ...