How can you use regex to determine if a multiline string contains any HTML tags?

Is there a method to determine if a multi-line string contains HTML tags(<>) within it?

var regex= /^(?!.*<[^>]+>).*$/;


console.log('istextWithoutHtml--', regex.test('Line1\nLine2'));\\ Expecting true, since it doesnt have html tags

\\ Expecting false for these combinations, since it contains html tags in it
\\ 'Line1<a>\nLine2'
\\ 'Line1\nLine2<p>'
\\ '<a></a>'
\\ '<\img>'
\\ '</a>\n</b>'

Trial 1

var regex1 = new RegExp(regex);
    
console.log('istextWithoutHtml---', regex1.test('Line1\nLine2')); \\ false (I am expecting true here)

console.log('istextWithoutHtml---', regex1.test('Line1<a>\nLine2')); \\ false

Trial 2

var regex2 = new RegExp(regex, 's');

console.log('istextWithoutHtml---', regex2.test('Line1\nLine2')); \\ true
console.log('istextWithoutHtml---', regex2.test('Line1<a>\nLine2')); \\ true (I am expecting false here)

Trial 3

var regex3 = new RegExp(regex, 'm');

console.log('istextWithoutHtml---', regex3.test('Line1\nLine2')); \\ true
console.log('istextWithoutHtml---', regex3.test('Line1<a>\nLine2')); \\ true (I am expecting false here)

Is there any way to achieve both HTML tag check in the multiple line string.

Answer №1

Here is a regex pattern you can use in JavaScript:

/^(?![^]*<[^>]+>)[^]*/.test(text)

Explanation:

  • ^ - signifies the start of the string
  • (?![^]*<[^>]+>) - specifies that immediately to the right, there should be no zero or more characters followed by <, one or more characters other than >, and then a > character.
  • [^]* - matches any zero or more characters as many times as possible

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

How can I dynamically display Material-UI's <MenuItem/> within a <DropDownMenu/> using ReactJS?

In my ReactJS + Material-UI project, I am working with an array named colors that contains different color strings such as "white", "blue", and "green. My goal is to render each color string as a <MenuItem/> within a <DropDownMenu/> component ( ...

Generate an array with an extra attribute included

When working with a third-party API that requires passing an array with an additional property, things can get a bit tricky. The standard approach involves creating a type like this: type SomeArgument = string[] & { foo: string }; doSomething(argument ...

Is there a way for me to retrieve the status of Jenkins jobs directly from an Angular JS page? I'm open to any suggestions on how to

I need to retrieve the status of a Jenkins job (either Success or Failure) from my AngularJS page. The AngularJS page I have is remotely triggering a Jenkins Job via URL. Once the Jenkins job is completed, I want to be able to display its status on the An ...

I am having trouble with a basic AJAX script using iframes. The first call returns a null element, but all subsequent calls work perfectly. What am I missing?

An AJAX script that performs the following sequence of actions: Creates a hidden iframe to buffer server-side output Loads PHP content silently into a div using the iframe Copies the PHP output from the server-side div to the parent page div The issue e ...

Managing null values in Typescript when they are greater than or equal to zero

I need to perform a simple check to see if a given variable is greater than or equal to 0. public print(value: any): void { if(value >= 0) { console.log('Greater than zero') } } The issue arises when the incoming variable has ...

What makes 'Parsing JSON with jQuery' unnecessary?

Just performed an ajax request with a query and noticed that my response is already in the form of a JavaScript object. When I try to parse the JSON using: var obj = jQuery.parseJSON(response); 'obj' turns out to be null, yet I can directly ac ...

How about sending cookies to different controllers?

We are currently developing a Spring-based application that consists of multiple controllers catering to different modules such as user authentication and analytics jobs. The issue we encountered involves setting cookies in our user controller for authenti ...

Is there a way to restrict the user to only submitting a rating once in vue.js 2?

Here is the code snippet I am working with: <div id="app"> <p>Communication:</p> <star-rating :value="3" name="communication"></star-rating> </div> You can see a demo and the full ...

Having trouble importing the router from a file using ES6 import/export syntax?

I recently made the switch to using ES6 syntax in my node app, specifically import NME from "./file" However, I ran into an issue in my app.js file when trying to import my routers. The error message I received was "Cannot find module '/Users/app/git ...

AngularJS is having trouble passing data to phpMyadmin's mySql database

I'm a beginner with AngularJS and it seems like I'm having trouble inserting data into my database. I've tried following a few instructions but it doesn't seem to be working. When I click on the submit button, nothing happens and no dat ...

Issues with Jquery Animate failing to complete its animation

My webpage has several animations running, and it seems that one particular animation is stuttering and not completing properly at times. The animation I have written is meant to animate percentage bars on the page. I attempted to add a timeout function ...

Fetching Unicode block specials using axios in getStaticProps with Next.js

Click here to view the code and data results My attempt using the fetch method was successful, but I encountered issues when trying to use 'axios' ...

Combining two objects retrieved using ngResource in AngularJS

Seeking guidance on merging two objects retrieved using ngressource. Every 5 seconds, I invoke my service to fetch a message and aim to append the new message with the older ones. The JSON message I receive: [ {"age": 0,"id": "my first tweet","name": "H ...

Differences between jQuery and Google Closure in terms of handling AJAX

Recently, I've been exploring the Google Closure Library for handling ajax calls. I came across an example that piqued my interest: goog.events.listen(request, "complete", function(){ if (request.isSuccess()) { // perform a cool action } els ...

TinyMCE - Optimal Approach for Saving Changes: keyup vs onChange vs blur

In the context of my Filemaker file, I am utilizing the TinyMCE editor. My goal is to automatically save any changes made by the user, whether it's typing, applying formatting, inserting an image, or making any other modifications. I have a function ...

Sending a batch request of a fixed size from an array of data using React and Axios

I am currently working with an Object array containing N (for example, 200) objects. My goal is to send these N objects to a remote API using Axios. However, I need to ensure that at any given time, there are only n (for example, 4) active requests awaitin ...

How to manage print preview feature in Firefox with the help of Selenium in the Robot Framework

Attempting to select the 'cancel' button in the print preview page on Firefox has proven to be a challenge. Despite my efforts, I am unable to access the element by right-clicking on the cancel option. Interestingly, Chrome allowed me to inspect ...

Removing elements from the MEAN stack

Facing a challenge with implementing a delete button for my list of posts. When the button is clicked, it only returns null instead of deleting the entry from the database. Here's my $scope: $scope.remove = function(post) { posts.remove(po ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

Alter the tab's color upon clicking the button

I am working on a multi-step form and I wanted to enhance the user experience by adding a button at the bottom of the page for easy navigation instead of relying on tabs at the top. Although the button functions as intended, there is an issue with the tab ...