Using JavaScript, create a regular expression with variables that can be used to identify and match a specific section of

Struggling to apply a regex (with 1 variable) to compare against a HTML code page stored as text.

The HTML code is separated into an array, with each element representing a snippet like the one below. Each element showcases details of fictional Houses (name, square footage, etc). My objective is to identify and match just one of these houses by extracting the text between the first TD tags. Specifically, I am interested in the VALUE (digits) inside the last INPUT tag of the form.

<TR BGCOLOR=#D4C0A1>
 <TD WIDTH=40%><NOBR>Luminous&#160;Arc&#160;2</NOBR></TD>
 <TD WIDTH=10%><NOBR>154&#160;sqm</NOBR></TD>
 <TD WIDTH=10%><NOBR>6460&#160;gold</NOBR></TD>
 <TD WIDTH=40%><NOBR>rented</NOBR></TD>
 <TD><TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0>
 <FORM ACTION= METHOD=post><TR><TD>
  <INPUT TYPE=hidden NAME=world VALUE=Olympa>
  <INPUT TYPE=hidden NAME=town VALUE="Yalahar">
  <INPUT TYPE=hidden NAME=state VALUE=>
  <INPUT TYPE=hidden NAME=type VALUE=houses>
  <INPUT TYPE=hidden NAME=order VALUE=>
  <INPUT TYPE=hidden NAME=houseid VALUE=37010>
  <INPUT TYPE=image NAME="View" ALT="View" SRC="" BORDER=0 WIDTH=120 HEIGHT=18>
</TD></TR></FORM></TABLE></TD></TR>

I formulated the following regular expression:

var regex = new RegExp(house + "[\\s\\S]+name=houseid value=([0-9]+)>", "i");

where house refers to the house name (e.g., Luminous&#160;Arc&#160;2) and the essential piece I seek is the houseid 37010.

I assumed this Regex would provide me with the needed result, yet houses[i].match(regex) consistently returns null. No matches are found in the string.

I've experimented with various methods, even trying to convert the HTML string into a DOM Object for parsing TR tags (unsuccessful). Progress seems within reach, but I'm currently at a standstill.

If anyone can discern why my regex isn't functioning correctly, it would be greatly appreciated.

Kenneth

Answer №1

To easily access the DOM in your HTML, you can add the string within a hidden div and retrieve it as needed.

Here is an example:

<div id="stringContainer"></div>
var searchstring = "Luminous&#160;Arc&#160;2";
searchstring = searchstring.replace(/&#160;/g, '&nbsp;') // Convert &#160; to &nbsp;

var c = document.getElementById("stringContainer");
c.innerHTML = '<table>'+houses+'</table>';
var h = c.getElementsByTagName('tr');

for(var i = 0, l = h.length; i < l; i++){ 
    var name = h[i].firstChild.nextSibling.getElementsByTagName('nobr')[0]; 
    if(name && name.innerHTML == searchstring){ 
        console.log(h[i].getElementsByTagName('input')[5].value) 
    }
}

Here's a working example

If we assume that the variable houses contains the following data:

var houses = '...'; // Data goes here

Answer №2

After testing your regex with Cerbrus's houses variable, it appears to be functioning correctly.
(Although I included the lazy quantifier ? in [\\s\\S]+, the regex still works without it.)

var house = "Luminous&#160;Arc&#160;2";
var regex = new RegExp( house + "[\\s\\S]+?name=houseid value=([0-9]+)>", "i" );

houses.match( regex )[1];    // "37010"

It seems that either your house variable contains the incorrect value or houses[i] is not accessing the intended string.

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

Integrate a post AJAX call into an Angular service for seamless functionality

I have come across an interesting scenario where I have to integrate old ajax code into a new Angular 10 application as per project requirements. Is it possible to directly run the existing ajax calls in the Angular service? Or, is there any node module ...

Error: The index "id" is not defined

Hey there, I have been working on fetching data from a JSON URL located at this link. However, I seem to be encountering an error that I can't quite comprehend. If anyone has any insights or solutions, I would greatly appreciate the help. Thank you in ...

Display an "add to cart" button and a discount image when hovering over

Currently, I am in the process of developing an Online Shopping website using PHP. To enhance the design of my website, I have implemented bootstrap. One specific query I have is how to display an 'add to cart' button and a discount image when a ...

How to Implement Double Click Functionality in VueJS

I am facing an issue with my table where the columns have varying widths. To implement sticky headers, I need to calculate the column widths accurately. Initially, I created a function that increases the column width when double-clicking on the header. Su ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

Event handling in jQuery is not triggered when the input value is modified using VueJS

Currently, I am working on a major project that was originally developed in jQuery. We are now in the process of refactoring it using VueJS. Here's how the scenario looks: html <div id="app"> <input :value='myVal'/&g ...

Having trouble with the jQuery function not working as expected? Can't seem to identify any errors in the code?

I'm attempting to capture the essence of moving clouds from this beautiful theme: (I purchased it on themeforest, but it's originally designed for tumblr) Now, I want to incorporate it into my wordpress website here: The code used to be under ...

javascript display an alert when the page is loaded

My customer wants to display an alert upon visiting a website. The problem is, alerts pause the page loading until the user clicks "Ok," and the client needs the page to continue loading in the background while the alert is visible. We could create a cus ...

Removing the previous value in React by shifting the cursor position - a step-by-step guide

I have successfully created a phone using React that saves the numbers in an input field whether you press the keys or use the keyboard. Although the phone is functioning well, I am facing an issue where pressing the delete button or backspace key always ...

Verify if Angular 2 route parameters have a legitimate value

Within an angular2 component, I have the following code: ngOnInit() { this.route.params .switchMap((params: Params) => this.elementsService.getElement(+params['id'])) .subscribe(element => { this.elementToEd ...

How to decode JSON data into a JavaScript array and retrieve specific values using index positioning

Upon receiving a json response via ajax, the code looks like this: echo json_encode($data); The corresponding ajax code is shown below: $.ajax({ url:"PaymentSlip/check", data:{val:val}, type: 'POST', succe ...

Avoid the need to refresh the HTML content every time there is a change in the Angular $

One of the challenges I'm facing is with a for loop in my JavaScript: for (var i=0;i<2;i++) { $scope.widget = widgets[i]; $scope.header = widgets[i].data.header; $scope.items = widgets[i].data.items; $scope.footer = widgets[i].data ...

Loop through the JSONP object to display its properties

When I receive this object through jsonp, it has the following structure: "item1": { "child1": { "nr": 123, "money": "USD", "Date": "12.12.2016, 17:00", "asw1": 13, "SpecialField" ...

Error: express is missing a closing parenthesis for the argument list

When running this code in the VS Code terminal, be sure to verify any errors that may occur. var express = require('express'); var app = express(); app.get('/', function(request, response) { response.send("hello world"); }); app.li ...

Attempting to update an AJAX field with the returned value, but it only updates after clicking away from it

Image of form utilizing AJAX & JS The current setup involves a maintainer that uses AJAX to update the "Calc" field in response to a number entered in the "Order No" field. The issue is that the "Calc" field does not update immediately after typing in the ...

Creating a .env file using Vanilla JavaScript to securely store and conceal tokens

I am currently working on a vanilla JavaScript project. Within the app.js file, I am making an API call to retrieve specific values. Initially, I tested the API using Postman by including all the necessary headers there and then implemented the code in my ...

When attempting to print a Rectangle on my webpage using JavaScript and taking user input, I encountered an error stating that 'str' is not defined

I'm trying to implement a feature where clicking on the "try it" button will prompt the user for the number of lines and then print that many lines in the form of a rectangle. However, when I run my code, nothing appears on the DOM and there is an err ...

Dealing with issues escaping unicode characters in JavaScript

Whenever I need to load data from an external file based on a specific event, I make use of the following jQuery code: $("#container").load("/include/data.php?name=" + escape(name)); An issue arises when the JavaScript variable "name" contains Unicode ch ...

Top storage solution for ExpressJS in the world of NodeJS

Embarking on the journey of creating my first substantial NodeJS application. My primary focus is achieving top-notch performance as the project involves a large AJAX (AngularJS) interface with numerous requests from multiple users. Currently in the proce ...

Ways to expand the dimensions of a Popup while including text

I am using a bootstrap modal popup that contains a Treeview control in the body. The issue arises when the node's text width exceeds the popup's width, causing the text to overflow outside of the popup. Is there a way to dynamically adjust the ...