How to eliminate all <style> tags across the board using Regex in JavaScript

Is there a way to utilize regex in JavaScript for removing all instances of <style>, <style type="text/css">, </style>, and <style type="text/css"/>? I want the outcome to only present the CSS without any style tags.

The code below seems to be ineffective for some reason.

str.replace(/<style\b[^<]*(?:(?!<\/style)<[^<]*)*<\/style>/gi,'');

Answer №1

After reviewing your question, the regex code provided below should be suitable

var regex = /((<style>)|(<style type=.+)|(<<\/style>))/g;
var str = `<style>
 styles
</style>

<style type="text/css">
 styles
</style>`;
const subst = ``;

// The substituted value will be stored in the result variable
var result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Check out the demo here


Update

Take a look at the updated regex which removes both the styles and the content within them.

var regex = /((<style>)|(<style type=.+))((\s+)|(\S+)|(\r+)|(\n+))(.+)((\s+)|(\S+)|(\r+)|(\n+))(<<\/style>)/g;
const str = `<style>
 styles
</style>

<style type="text/css">
 styles
</style>

non html content`;
var subst = ``;

// The substituted value is saved in the result variable
var result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Click here for more details

Answer №2

To start off, make sure to correct your regex by using \s+ instead of \b and ensuring the type= argument is set correctly. Also, consider adding the tag variant for better accuracy.

/((<style>)|(<style\s+type=(?:".*"|'.*')\/?)|(<\/style>))/gi

Keep in mind that your string will be read by two engines - first Javascript, then the Regex engine. Make sure to escape characters like \ accordingly.

.replace(/((<style>)|(<style\s+type=(?:".*"|'.*')\\/?)|(<\\/style>))/gi,'');

Give it a test run here!

Answer №4

Improvement for eliminating inline style:

.replace(/ design=("[^"]*")|('[^']*')/g, "");

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

Implementing slideDown() functionality to bootstrap 4 card-body with jQuery: A step-by-step guide

Here is the unique HTML code I created for the card section: <div class="row"> <% products.forEach(function(product){ %> <div class="col-lg-3 col-md-4"> <div class="card mb-4 shadow "> &l ...

Error: The provided `anchorEl` property for this component is invalid

While working on my React 18.2 app with MUI 5.10.5, I encountered an issue trying to create a <Menu /> element that should open when a button is clicked. The menu does appear, but the positioning seems off as it displays in the top-left corner of the ...

Issues with React useState persisting new values between useEffect intervalsHere is a rephrased

I am attempting to store jokes and log a new value every time the interval runs (triggered by a get call) after 5 seconds. However, for some reason, the value is not rendering anything after each interval. I'm not certain if the jokes are actually bei ...

How can I incorporate a standalone Vuetify component into my Nuxt.js project?

Using Vuetify with nuxt.js specifically for the dashboard layout - how can I achieve this in my nuxt.config.js file? modules: [ //['nuxt-leaflet', { /* module options */}], 'bootstrap-vue/nuxt', '@nuxtjs/ax ...

Utilize Javascript to establish a fresh attribute by analyzing other attributes contained in an array within the object

Currently, I am working on a data structure that looks like this: masterObject: { Steps: [ { step: { required: false, }, step: { required: false, }, step: { required: false, }, }, ] } ...

Organize the array object by roles using mapping and grouping techniques

Given an object array with roles as keys and values, I want to group them according to the roles assigned. Here is the sample data: { users: [ { firstName: 'Will', lastName: 'Jacob', email: '<a href="/cd ...

Ways to monitor the status of a server request using jQuery (ajax)?

I am currently working on a PHP application that involves users submitting forms to the server via ajax (jQuery). The server needs to insert a large number of records into a MySQL database, which may take some time due to various calculations. My question ...

The file "tfjs_binding.node" could not be located in the directory where @tensorflow is installed

After attempting to utilize certain functionalities of TensorFlow, I encountered an error indicating that "tfjs_binding.node" was not found in the @tensorflow installation folder. I made sure to install Python 2.7 as a prerequisite for TensorFlow and veri ...

Select multiple rows by checking the checkboxes and select a single row by clicking on it in the MUI DataGrid

I am currently utilizing the MUI DataGrid version 4 component. The desired functionalities are as follows: Allow multiple selections from the checkbox in the Data Grid (if the user selects multiple rows using the checkbox). Prevent multiple selections fr ...

React Redux components are failing to render after changes are made to the state array

I'm fairly new to using React, Redux, and Thunk in my project. Right now, I'm facing an issue where I fetch an array from an API call in my action/reducer, but it doesn't re-render in the connected component/container that's hooked up t ...

I have been working on incorporating a menu item in React, but I keep encountering an error

I am using the MenuItem component to create a dropdown menu in my React project. Despite importing the necessary package, I am encountering an error when running the server. I have searched for solutions but haven't found a definitive me ...

Exploring the Benefits of Combining Vue.js with Laravel

Being a newcomer to Vue, I decided to try it out in a recent project and quickly understood why it's so popular. Everything was running smoothly until I tested it in IE, where nothing seemed to work at all. Encountering errors like Object doesn' ...

Encountered a problem when trying to import the function "createToken" into a Node.js middleware

I have developed a model called users in which I included a method named generateToken for generating web tokens. This model is being used with the Sequelize ORM. module.exports = (sequelize, Sequelize) => { const Tutorial = sequelize.define("u ...

Enhance the appearance of the jQuery document.ready function

I'm attempting to customize the jQuery document.ready function <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript> $(function() { c ...

Encountering a mixed content error in Internet Explorer 8 due to the Nivo slider jQuery?

I am encountering an issue with the Nivo jQuery slider on my HTTPS website, as it appears to be generating a mixed content error in Internet Explorer 8. Despite posting on the Dev7 Studios forum and conducting extensive research on the IE 8 mixed content ...

The reason why JavaScript condenses two or more spaces into just one space

After encountering a problem with my HTML/JS/Angular script, I created a simple demo to illustrate the issue. Although I have found a solution, I still wanted to seek advice from experts. <body ng-app> <div ng-controller='abc'> ...

Creating a reusable field for reactive forms in Angular: A step-by-step guide

I need assistance with creating a versatile field component for reactive forms, but I am facing challenges in retrieving the value from the custom-input element. <form [formGroup]="form" (ngSubmit)="submit()"> <custom-input i ...

Performing a synchronous loop with Javascript promises

I've been struggling with a seemingly simple task that's been causing me immense frustration. Despite scouring the entire Internet, none of the solutions I found seem to directly address my specific issue. It all stems from a follow-up question r ...

What is the method for breaking down a React useState hook into separate variables within a namespace?

Personally, I like to group React props into namespaces for better organization. When using the useState hook, I follow this approach. function MyComponent() { const [todoCount, setTodoCount] = useState(100); const [doneCount, setDoneCount] = useSta ...

In my React application, I have integrated p5 sketches that constantly loop and repeat

Currently facing a challenge integrating p5 sketches into my React App. I've tried adjusting the z Index of the toolbar to place the p5 elements underneath, but they end up repeating instead. Check out the repository here (sketches can be found in the ...