Using Javascript regex to validate strings without any backslashes present in the text

Having an issue with a JavaScript regex that needs to comment out all <script> tags inside a <script> tag except the first one with the id "ignorescript".

Here is a sample string to work with:

<script id="ignorescript">
    var test = '<script>test<\/script>;
    var xxxx = 'x';
</script>

The script tag inside ignorescipt has an extra backslash because it is JSON encoded (from PHP).

Here is the desired final result:

<script id="ignorescript">
    var test = '<!ignore-- <script>test<\/script> ignore-->;
    var xxxx = 'x';
</script>

The following example is functional:

content = content.replace(/(<script>.*<\\\/script>)/g,
    "<!--ignore $1 ignore-->");

However, I need to ensure it does not contain the keyword "ignorescript". If that keyword is present, no replacement should occur. Otherwise, add ignore comments to the entire script tag. So far, the regex looks like this:

content = content.replace(/(<script.((?!ignorescript).)*<\\\/script>)/g,
    "<!--ignore $1 ignore-->");

It somewhat works, but not as expected. There is also an issue with the ending tag backslash, so I modified it to this:

content = content.replace(/(<script.((?!ignorescript).)*<\\\/script>)/g,
    "<!--ignore $1 ignore-->");

Now it does not find anything at all.

Answer №1

Success, it's finally up and running.

Check out the updated regex below:

/(<script(?!\sid="ignorescript").*?<\\\/script>)/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

The execution of JS code is being hindered by PHP codeigniter

Utilizing some pre-owned code in my current project The code snippet below is responsible for adding a product to the wishlist within the view <p class="p"><a<?php echo "onclick='addtowishlist($product->id)'"; ?>>Add To W ...

Displaying the specified item within an array using AngularJS

My application features a group of 'players' each with their own unique attributes that I want to showcase within a modal window and cycle through. The user interface is structured like this: <!-- Score Round Modal --> <div class="mo ...

Contrasting Template Helper and Template Variable in Meteor.js

What sets apart the use of a Template Helper from a Template Variable (if that's not the right term)? How do you determine when to utilize each one? In the following example, both Template.apple.price function and the quantity function in Template.ap ...

Can the variable name within a function be retrieved?

How can I retrieve the variable name (user_name1 or user_name2) from a sample function (GetUserName()) within itself? This variable name is required to create an object with the same name on the server side for data synchronization purposes. function GetU ...

Encountering a 'type error' stating that $(...).modal is not a valid function

While working on a REACT project, I encountered an issue while trying to create and edit a function for updating notes by users using bootstrap modals. The error message that appeared is: Uncaught (in promise) TypeError: jquery__WEBPACK_IMPORTED_MODULE_1__ ...

The function chrome.notifications.create() is producing incorrect notification IDs upon clicking

Greetings for my first post here. I've been struggling with an issue in a personal project lately. I remember coming across a similar topic on this forum before, but now I can't seem to find it. As far as I recall, the question went unanswered. ...

Is there a way to run /_next/static/xxx.js using a script tag?

I have customized my next.config file (webpack) to generate a static JavaScript file (.next/static/loader.js). The original loader.js is an Immediately Invoked Function Expression (IIFE): (function stickerLoader(){ alert('Hello'); // ... so ...

What is the best way to stop a Vue.js state using clearInterval()?

In my Vuex code, I currently have the following: export default new Vuex.Store({ state: { intervalVar: 0 }, mutations: { SET(state, {key, value}) { state[key] = value }, }, actions: { doSo ...

Checkbox in Angular FormGroup not triggering touched state

There seems to be an issue with the Angular form when checking if the form is touched, especially in relation to a checkbox element. Despite the value of the checkbox changing on click, I am seeing !newDeviceGroup.touched = true. I'm not quite sure wh ...

Organize a collection of items in AngularJS

Consider the following array: var members = [ {name: "john", team: 1}, {name: "kevin", team: 1}, {name: "rob", team: 2}, {name: "matt", team: 2}, {name: "clint", team: 3}, {name: "will", team: 3} ]; I want to create an unordered list for each ...

Tips for automatically scrolling mat-select option to the top when mat-select is closed

Is there a way to automatically scroll the mat-select options to the top after closing it? I am faced with a situation where I have numerous options in my mat-select dropdown. If I select an option from the bottom and then close the mat-select, is there a ...

Clicking on ng-click can lead to the dissociation of the Angular factory

My situation involves a factory with a series of prototypes that need to call each other. The issue arises when the reference to "this" is mistakenly applied to the html template instead of the original factory class when using ng-click. For example: ang ...

Select a division and retrieve the identification of a different division

I am looking to trigger an event by clicking on one element and extracting the ID from a separate, unrelated div. Here is my attempt: $(".map_flag").on("click",function(){ var selectedID = ($(this).attr("data_modal")); $("#" + selectedID).fade ...

Error injecting Angular components

Here is the structure of my HTML file: <html> <head> <title>PLD Interaction pattern</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> </head> <body ng-app="myT ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

AngularJS special feature: enhance controllers and views by adding notification capabilities

What is the most efficient method for integrating common notification features into necessary controllers in AngularJS? The objective is to establish local notifications that can be effortlessly included or removed from any controller. Key factors includ ...

How can I set a value using document.getElementById(idPopUPImage).innerHTML to create a static popup in Leaflet?

I added a leaflet map to my project which you can find on Codpen In the map, I've included a button key that displays an image in a popup when clicked. However, after closing the popup and reopening it, the image doesn't show unless I click the ...

Guide on assigning a callback function in JavaScript

In this code snippet, I am initializing a new object variable and passing an object as an argument: const newObj = new customObject({ first : $('#fname').val(), last : $('#lname').val(), fn : function() { alert(this ...