Enhancing web design with JavaScript regex to replace matching width attributes

Currently, I am utilizing RegEx to target a more specific subset of TinyMCE HTML within a textarea. The widths are causing some overflow issues, so I am experimenting with some test code in JavaScript.

One thing that perplexes me is why $3 is not only capturing "1000px", but also includes everything following the table tag in the document?

<script language="javascript">
  // adjust table width
  function adjustTable(elem0, elem1) {
    // for debugging purposes, display results in a div
    elem1.innerHTML = elem0.innerHTML.replace(/^(.*)(\u003Ctable.*?\s*?\w*?width\u003D[\u0022\u0027])(\d+px)([\u0022\u0027].*?\u003E)(.*)$/img, "$3");
  }
</script>

<button type="button" onclick="adjustTable(document.getElementById('myTable'), document.getElementById('myResult'))">RegEx</button>

<div id="myTable">
  <table width="1000px">
    <thead>
      <tr><th colspan="3">Table Header</th></tr>
    </thead>
    <tbody>
      <tr><td>alpha</td><td>beta</td><td>gamma</td></tr>
    </tbody>
  </table>
</div>
<textarea id="myResult">
</textarea>

While I comprehend that RegEx and HTML should not be mixed due to their intricacies, I am striving to render a printable subset of HTML.

I am confused by the multiple matches that are being returned.

Here is the resulting output for $3.

1000px
        <thead>
          <tr><th colspan="3">Table Header</th></tr>
        </thead>
        <tbody>
          <tr><td>alpha</td><td>beta</td><td>gamma</td></tr>
        </tbody>
      </table>

While it does capture "1000px", there seems to be extra content after the table tag, which is unexpected as I believed I was specifying a match within the table tag. Any thoughts on this?

Answer №1

To troubleshoot this issue, let's log the entire result of the regular expression:

function adjustTable(elem0,elem1) {
    // debugging, place results in div
    console.log ( (/^(.*)(\u003Ctable.*?\s*?\w*?width\u003D[\u0022\u0027])(\d+px)([\u0022\u0027].*?\u003E)(.*)$/img).exec(elem0.innerHTML) );
}

The output is:

[
0: "  <table width="1000px">"
1: "  "
2: "<table width=""
3: "1000px"
4: "">"
5: ""
index: 1
input: "↵  <table width="1000px">↵    <thead>↵      <tr><th colspan="3">Table Header</th></tr>↵    </thead>↵    <tbody>↵      <tr><td>alpha</td><td>beta</td><td>gamma</td></tr>↵    </tbody>↵  </table>↵"
]

If you need to retrieve the value "1000px", you can utilize the following code:

(/^(.*)(\u003Ctable.*?\s*?\w*?width\u003D[\u0022\u0027])(\d+px)([\u0022\u0027].*?\u003E)(.*)$/img).exec(elem0.innerHTML)[3]

Answer №2

When using JavaScript, be aware that the dot does not match linebreak characters. Additionally, if you include the /m modifier, the $ will match the end of lines, not just the end of the file.

As a result, the (.*) in your regex may not match anything, leaving the remaining string unchanged when you replace the match with $3 (which contains 1000px).

For more information, you can visit regex101.com.

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

save function ajax failure

I have created a function that adds a row after confirmation. The issue is that after submitting, the tables do not reload and show an error alert. In reality, the data is successfully saved but I need to refresh the page for the table to reload. Below is ...

How can I use VB codebehind in ASP to display a dialog box to the user asking for a yes or no response?

I am faced with a scenario where a user has chosen a product, the system has retrieved the product record, and the backorder flag has been set. I need to inquire if the user still wants to proceed with including the product in the order. However, I am stru ...

Using JQuery to rebind() after resetting the count

In my game, I have implemented a feature to ensure that the start button can only be clicked once each time it appears in order to prevent the function from loading multiple times. I wrote some code that tracks the number of clicks and unbinds the click e ...

extract data obtained from an AJAX call

I am working on an ajax request in my code: var rootURL = "http://localhost/myapp/api/api.php"; $.ajax({ type: 'GET', url: rootURL + '/favourites', dataType: "json", success: function(list) { }, error: f ...

"Process the contents of a file by reading it line by line in a

Currently, I am reviewing the documentation for the nodejs readline module in order to tackle a task that involves reading a very large file line by line. The solution using readline seems promising, although I require it to read lines synchronously - mean ...

Utilize getElementsByClassName to dynamically alter the appearance of specific elements upon triggering an event

I'm attempting to utilize onmouseover="document.getElementsByClassName().style.background='color'" in order to switch the color of all divs with a specified classname to a different color when hovering over another element on the page. ...

What is the reason behind the improved performance I experience in Chrome with the Developer Console open?

Currently, I am developing a small canvas game completely from scratch using pure JavaScript. This game utilizes a 2D lighting algorithm that is akin to the one found here. It features only one light source and 25 polygons, resulting in approximately 30,0 ...

The audio.play() HTML element fails to function in Chrome, preventing the audio from playing

I'm experiencing an issue with playing audio in Chrome when the audio.src is not called before the play call, but Firefox seems to handle it fine. Does anyone have any suggestions? You can check out the fiddle link below - http://jsfiddle.net/vn215r2 ...

How do I navigate to the homepage in React?

I am facing an issue with my routes. When I try to access a specific URL like http://localhost:3000/examp1, I want to redirect back to the HomePage. However, whenever I type in something like http://localhost:3000/***, I reach the page but nothing is dis ...

What is the method for selecting the desired month on a primeng calendar with multiple selection enabled?

I am looking for a solution to make my inline primeNg Calendar display the month of a specific date in the model, and when I remove dates from the model, I want it to show the current month. I have tried using defaultDate={{value}} and minDate={{value}}, a ...

I am unsure how this type of jQuery AJAX data : () will be interpreted

I'm not a beginner nor an expert in jQuery. I'm modifying a jQuery code for opencard checkout section. There is a Javascript file in this section that sends data to the server. I came across an AJAX request with data structured like this: url: ...

What is the process for retrieving data from a form input field?

I am currently working on a form that will dynamically populate with data from a database. Here's how it is supposed to function: the user inputs the company number, and then the form queries the database to see if the number exists. If it does, the c ...

Achieving a transparent inner box-shadow effect on hover: a step-by-step guide

Is there a way to make the black ring transparent upon hover by changing box-shadow: 0 0 0 5px #000, 0 0 0 10px green to box-shadow: 0 0 0 5px transparent, 0 0 0 10px green? It doesn't seem to be working for me. Any suggestions on how to achieve this ...

Transferring data securely via URLs

I need advice on securing a JavaScript function that passes values into URLs in order to navigate to another page. What precautions should I implement to prevent manipulation of this process? This is the code snippet I am currently using: window.location ...

The correct method for implementing server-side rendering with JavaScript

My website consists of multiple pages and utilizes React as a widget toolkit, with different bundles on each page. I am facing an issue where some widget state persists within a login session, and when the user revisits the page, the components should relo ...

When navigating using the next and back buttons, the active state in Angular is automatically removed

Looking for some assistance with my quiz app setup. Each question has True/False statements with corresponding buttons to select T or F. However, when I click the next/back button, the active class is not being removed from the previous selection. As a beg ...

"Implementing a function triggered by a change event within a concealed input

I am working with two AJAX functions. The first function takes the input from the first field, concatenates a string to it, and then updates the value of the second hidden input field. However, the second function is supposed to detect any changes in thi ...

Arranging containers in a fixed position relative to their original placement

A unique challenge presents itself in the following code. I am attempting to keep panel-right in a fixed position similar to position: relative; however, changing from position: relative to position: fixed causes it to move to the right side while the left ...

Top method for displaying radio buttons as switchable buttons within a web form

I want to customize the appearance of my radio buttons on a form to make them look like toggle-able HTML buttons, similar to the examples shown in these Bootstrap examples. By using Flask, Bootstrap, and jinja2, I've successfully converted my radio bu ...

Show various Bootstrap Alert Messages based on the type of error detected?

Trying to figure out how best to explain this, here it goes! I am working on a website and I want to incorporate alert messages. Check out some examples here. Depending on the form inputs, I need different alerts to be displayed. PHP will validate the in ...