IT Nota

  • Home
  • How To
  • .NET
  • WordPress
  • Contact
You are here: Home / How To / How to Use RegEx to Replace Text in JavaScript

How to Use RegEx to Replace Text in JavaScript

Just to build on top of the code from the previous post. This time, there is a page on a Web Forms application with a text that needs to be eliminated, but we no longer have the ability to re-compile. Fortunately, the change is cosmetic so we can resort to using plain vanilla JavaScript to solve this.

Again, the provided HTML, although it was from a real legacy application, it has been cut short so it’s not too distracting. What we need to do here is to remove Obsolete Service: and its content from the list of current services as displayed below:

HTML search string to be removed with JavaScript

This part of HTML was generated dynamically by a Web Forms and at this point recompiling is not an option. So what we wanted to do is to let the application still generates the page and we intercept the result with JavaScript and modify it after the fact.

<table>
  <tr bgcolor="#e4f4ff">
    <td valign="top">
      <span id="lblservicemsg"><b>Current Services:</b></span>
    </td>
    <td valign="top">
      <span id="lblCurrentServices" class="formtxt"><strong>Mobile: </strong> MobileCarrier <br><strong>Internet:
                </strong> Internet Provider <br><strong>Obsolete Service: </strong> ABN39482 <br><strong>Messaging: </strong>
                iMessage<br></span>
    </td>
    <td valign="top">
      <input type="submit" name="btnAddServices" value="Edit Services"
             onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btnAddServices&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))"
             id="btnAddServices" class="formbtn" style="width:176px;">
    </td>
  </tr>
</table>

Studying the pattern above, it looks like the Obsolete Service: begins with a <strong> tag and ends with a <br>. However, it’s also known that between the closing </strong> tag and <br>, there could be more than one data point. So we can do a search using JavaScript to match the text Obsolete Service: and we need to use Regular Expression to match all entries between the closing </strong> tag and <br>.

Using the same logic of JavaScript to find the text in the previous post, we just need to grab the HTML text using innerHTML. Then we need to remove the instance of Obsolete Service using Regular Expression for the pattern matching.

We can use RegExr: Learn, Build, & Test RegEx website to try to match the pattern we’re looking for. And from trial and error, we found that to include all strings until the next occurence of <br> is by using (.+?)<br>. So the final pattern to use to capture what we want is <strong>Obsolete Service:(.+?)<br>.

RegEx pattern test for JavaScript

At this point, we can copy the pattern and paste it to our JavaScript code by substituting it with the variable searchText as such: `<strong>${searchText}(.+?)<br>` and assign the value to a constant regString. So whenever the script finds a match of this pattern, it will replace it with an empty string.

  const searchText = 'Obsolete Services:'
  document.addEventListener('DOMContentLoaded', function () {
    const spanTags = document.querySelectorAll('span')
    for (let i=0; i<spanTags.length; i++) {
      if (spanTags[i].innerHTML == searchText) {
        const elementId = spanTags[i].id
        // Get innerHTML
        const element = document.getElementById(elementId)
        const getInnerHTML = element.innerHTML
            
        // Use Regular Expression
        const regString = `<strong>${searchText}(.+?)<br>`
        let regex = new RegExp(regString)
        const replaceText = getInnerHTML.replace(regex, '')
        element.innerHTML = replaceText
      }
    }
  })

That’s it. Now, when the page is loaded, Obsolete Service is removed from the page.

Before

HTML search string to be removed with JavaScript

After

HTML string removed with JavaScript

Further Reading

How to Get HTML Elements with textContent in JavaScript

August 10, 2021 Filed Under: How To Tagged With: JavaScript

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Buy me a coffee Support this site
Buy Me a Coffee?

Categories

  • .NET
  • Coding
  • Cybersecurity
  • Database
  • How To
  • Internet
  • Multimedia
  • Photography
  • Programming
  • Resources
  • Review
  • Tips and Tricks
  • Use Case
  • WordPress
  • Writing

Recent Posts

  • How to Check Installed .NET Framework Version
  • How to Remove .NET Runtime and SDK on Mac
  • How to Solve Intermittent 403 Error in IIS
  • How to Show Hidden Folders and Files in Mac Finder
  • How to Solve MS Office VBA Compile Error UserAuthentication

Recent Posts

  • How to Check Installed .NET Framework Version
  • How to Remove .NET Runtime and SDK on Mac
  • How to Solve Intermittent 403 Error in IIS
  • How to Show Hidden Folders and Files in Mac Finder
  • How to Solve MS Office VBA Compile Error UserAuthentication
  • RSS

Tags

.NET Access AdSense ASP.NET Cdonts Dll Classic ASP Code Editor ETL FSharp Genesis Framework Git Google HP Asset Manager HTML HTML5 Hugo IIS Information Security Internet Internet Information Services iOS JAMStack Linux macOS Microsoft Microsoft SQL Server MVC PHP Python Simple Mail Transfer Protocol Smtp Server Social Media SQL SQL Server SSIS SSMS SSRS Sublime Text Visual Studio Visual Studio Code VPN Windows Windows 8 Windows 10 Windows Server

Copyright © 2011-2022 IT Nota. All rights reserved. Terms of Use | Privacy Policy | Disclosure