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

Is there a way for me to display an alert notification when a website requests access to additional storage on my computer?

Is there a way to set up an alert notification in Internet Explorer when a website requests additional storage on your computer? The notification would ask: Do you want to grant permission for this website to use additional storage on your computer? ...

Tips for displaying the contents of a URL within a div element

Is there a way to load a new page into a <div></div> without opening a separate tab? I tried using an iframe, but that method is not recommended and it includes scroll bars. <div id="iframeLogin"><a href="first.php" target="_self"> ...

Caution when using a React form: Value of `true` has been detected for a non-boolean attribute `validate`

I am trying to address a warning message that I have received index.js:1 Warning: Received true for a non-boolean attribute validate. If you want to write it to the DOM, pass a string instead: validate="true" or validate={value.toString()}. I ...

Configuring a Meteor.js application requires defining variable scopes for templates in order to manage

Is there a way to define a variable that is limited in scope to a specific template? I want this variable to be accessible by multiple helpers within the template, but not outside of it. For example, how can the game variable be shared between two templat ...

What is the best way to show only the weekdays on the x-axis?

My goal is to create a scatter-linked graph using D3.js, showcasing the people count for various shifts on different dates in January 2020. Here is the code snippet I am working with: <!DOCTYPE html> <html lang="en" > <head> & ...

Tips for successfully transferring values from an onclick event in JavaScript to a jQuery function

I am encountering a challenge with an image that has an onclick function associated with it. <img id='1213' src='img/heart.png' onclick='heart(this.id)'> This particular function needs to be triggered : function heart ...

Hide and show submenus with jQuery while ensuring that the initial submenu remains visible, along with the main menu

I am struggling to figure out how to make the first message active by default along with its corresponding menu selection in my navbar. I have implemented a show/hide functionality on the main menu click, but currently only the menu is being set as active ...

Discord bot struggling to reach every user in the server

After creating a discord bot with Discord.js, I was able to retrieve all the users from my server. However, lately I noticed that it is only returning 59 members out of the 300+ in total. I want to ensure that I am able to access all the users as before. ...

Calling a function within another function

In my code, I have a function that formats the price and retrieves the value needed for refactoring after upgrading our dependencies. I'm struggling with passing the form value to the amountOnBlur function because the blur function in the dependencie ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = ...

Getting a 406 (Not acceptable) error when trying to perform an AJAX action in Rails 4

I am attempting to automatically refresh a specific partial view every 60 seconds on the homepage. To make it easier to manage, I have divided the actions into two routes. However, I am encountering an issue with the respond_to block and could use some ass ...

Extract JSON content from an array's values containing underscores

I am currently working with an array of objects and need to implement a filter on it. The objects in the list contain an owner_id property within the JSON... Currently, I am looping through all the items in the array. However, I want to exclude those wher ...

Retrieve HTML classes within JavaScript textual templates

<!-- TEMPLATE UPLOAD --> <script id="template-upload" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-upload fade"> <td class="name"><span>{%=file.name%}</span></td> <td ...

In TypeScript, this regular expression dialect does not permit the use of category shorthand

Recently, I attempted to implement a regular expression in TypeScript: I ran the following code: const pass = /^[\pL\pM\pN_-]+$/u.test(control.value) || !control.value; To my surprise, an error occurred: "Category shorthand not allowed in ...

Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what&ap ...

React: maintaining referential equality across renders by creating closures with useCallback

I want to make sure the event handling function I create in a custom hook in React remains referentially equal across renders. Is it possible to achieve this using useCallback without specifying any variables it closes over in the dependencies list? Will o ...

What is the process for validating a JWT token using an x.509 certificate in a Node.js environment?

I need assistance with making a node script capable of validating a JWT token. I possess the public key, which is an x.509 certificate, along with the JWT itself. My attempt to utilize https://github.com/auth0/node-jsonwebtoken proved unsuccessful as it d ...

Adjusting the Stripe Button to Utilize a Unique Button Class

I have a stripe button on my website and I want to add my custom class to it. I discovered that manually creating the CSS for it can work, but I prefer to maintain consistency across all buttons on my site by using my custom class. No matter what I attemp ...

Retrieving a value from an array at random to assign to a different variable

I have different options for a specific variable depending on the scenario --> var lowSpeed = Math.random() * (45 - 30) + 30; var mediumSpeed = Math.random() * (60 - 45) + 45; var highSpeed = Math.random() * (80 - 60) + 45; var highwaySpeed = Math.rando ...

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...