Mastering the art of looping and implementing logic in JavaScript using Regular

Unsure if it is possible to achieve this using regex under JavaScript, but I found the concept interesting and decided to give it a try. I wanted to clean up some HTML code by removing most tags completely, simply dropping them like

<H1><img><a href ....>
. This seemed relatively straightforward (taking inspiration from another post by karim79 Remove HTML Tags in Javascript with Regex).

function(inString, maxlength, callback){
        console.log("Sting is " + inString)
        console.log("Its " + inString.length)

        var regex = /(<([^>]+)>)/ig
        var outString =  inString.replace(regex, "");
        console.log("No HTML sting " + outString);
        if ( outString.length < maxlength){
            callback(outString)
        } else {
            console.log("Lets cut first bit")
        }
    }

Then I began considering whether there was a way to control the execution of regex. For example, if I want to preserve certain tags like b, br, i and maybe change H1-6 to b. In pseudo code, something like:

for ( var i in inString.regex.hits ) {
   if ( hits[i] == H1 ) {
         hits[i] = b;
   }
}

The challenge here is that I want the non-HTML text to remain unchanged, while I only want to remove the HTML tags by default. One approach could be to modify the tags I want to keep. For instance, changing <b> to [[b]], then reverting them back to <b> once all unwanted tags are removed. Here's an attempt at implementing this logic (specifically for 'b', and unsure if the following code would function as intended):

 function(inString, maxlength, callback){
        console.log("Sting is " + inString)
        console.log("Its " + inString.length)

        var regex-remHTML = /(<([^>]+)>)/ig
        var regex-hideB = /(<b>)/ig
        var regex-showB = /([b])/ig
        var outString =  inString.replace(regex-hideB, "[b]");
        outString = outString.replace(regex-remHTML, "");
        outString = outString.replace(regex-showB, "<b>");
        console.log("No HTML sting " + outString);
        if ( outString.length < maxlength){
            callback(outString)
        } else {
            console.log("Lets cut first bit")
        }
    }

Is there a more intelligent way to approach this? Writing code that can identify a piece of HTML tag and then execute specific actions against the match.

Answer №1

Instead of relying solely on Regex, Tim Biegeleisen suggests using a parser which could offer a more effective solution.

Furthermore, to have better control over the changes made by the regex, one can utilize a callback function with String.prototype.replace:

let input = "<div><h1>HELLO World</h1></div>";

let output = input.replace(/(<([^>]+)>)/gi, (val) => {
    
    if(val.indexOf("div") > -1) {
      return "";
    }
    
    return val;
  })
;

console.log("output:", output);

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

What is the best way to retrieve the promise that encountered an error in the catch block while using async/await

I'm currently in the process of converting code that used .then/.catch to instead use async/await. One particular challenge I'm facing is how to access the original promise that fails within the catch block, for logging purposes. Here is the ori ...

What is the best way to make an array with values from a checkbox list?

I am working on a project that involves rendering a list of products categorized into different categories. Users can select these categories using checkboxes. Are you interested in learning how to create an array containing the selected values from the ch ...

Append a constant string to the conclusion of the route parameter

Using React Router v6.4.1, I am aiming for a consistent conclusion to a series of dynamic routes. Specifically, I want my product detail routes to always end with "-product". For example, if the path is "/shaver-900-product", it should activate my Produc ...

Consolidating multiple inputs into a single saved value

How can I combine three input values into one input field using onchange event in JavaScript? <script type="text/javascript"> function updateInput($i){ $('updateval').val($i); } </script> <input type="text" onchange="updat ...

A guide to creating a script that can iterate through every .m and .h file, and substitute a specific line of code

I am looking to create a script that will search through all files with either a .m or .h extension, and locate the following pattern: #import <React/ThisCanBeAnyText.h> Once this pattern is found, I want to replace it with the following: #if __ha ...

Tips for designing a search bar using Angular

search : ____________ I am interested in designing a search bar functionality that automatically triggers when the user inputs 8 or more characters. The input text will be stored in a variable, the search bar will be reset, and the backend API will be che ...

Using Selenium to Retrieve HTML Content Between Two Tags

How can I extract the following data from the provided HTML using Selenium 4 and XPath in Python? Message names (e.g. Message 1), Received timestamp (e.g. Received: 214-2342-234), and the most challenging part: message text (e.g. This is message nr. 1 it ...

Handling onChange events for several typescript <Select> elements

As a non-TS developer, I'm delving into the realm of multiple selects and dropdown menus with Material-UI's select component. Progressing from a basic setup, I successfully implemented a single select but now face a challenge in adding another dr ...

Unable to display shadows in Three.js

I've hit a roadblock with the shadow effect at the moment, despite trying various solutions for hours, it's still not appearing. Can anyone point out what I may have done incorrectly? Below is the code snippet for my current scene: //Setting up ...

Is it possible to utilize $(document).ready() within an ASP.NET page?

I am encountering an issue while attempting to use $(document).ready() as shown in the image above. What steps should I take to troubleshoot and resolve this problem? Update 23/05/2011 10:54 A new insight has come to light. The page I am working on inher ...

The Bootstrap 4 Modal has a one-time activation limit

It seems that I mistakenly created two modals. The issue arises when I open either of them for the first time and then close it, as from that point on, neither modal is able to be opened again by performing the same action that initially worked. https://i ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

What could be causing the mysql-event to not function properly in a Node.js environment?

const MySQLEvents = require('mysql-events'); const databaseInfo = { host: 'localhost', user: 'root', password: '' //blank password }; const mysqlEventWatcher = MySQLEvents(databaseInfo); console.log(mys ...

Discovering the URL of an AJAX request on any given website

Is there a way to retrieve the URLs of AJAX requests that are sent by the current page on a website using a browser or another tool? ...

Verify the accuracy of the properties received from mapStateToProps in a functional React Redux component

I am working with 3 components: TypeList, ConnectedType (connected through connect(mapStateToProps)(Type)), and the component Type. Type will receive props from both TypeList (onClick, name) passing props to ConnectedType as well as ConnectedType's ma ...

Assessing efficiency through the lens of SeleniumWebDriver versus native JavaScript

Imagine a scenario where an action is triggered by clicking a button on a webpage. Let's say this action takes X seconds to complete, and during this time a div appears in the center of the page. Once the action is done, the div disappears, and focus ...

What is the reason for the text not being written continuously in the textfield?

Looking to create a page for collecting user information. This is a Codesandbox.io page where the issue arises. https://codesandbox.io/s/material-demo-z1x3q?fontsize=14 When I try to input "d" continuously in the 성별* textfield, I can only enter "d" ...

What is the best way to implement a keypress event in this code?

As a JavaScript and jQuery newbie, I have a question regarding adding a simple key press action to this code. How can I implement functionality where pressing the Right Arrow key takes me to the next image, and pressing the Left Arrow key takes me to the p ...

`Issues with AJAX PHP file upload`

I've been working on an AJAX PHP upload script, but I'm facing some issues. Once the user selects an image to upload, it should display in the specific div container specified in my javascript file (which is working fine). However, I believe ther ...