Pete
Pete

Reputation: 3451

How to JavaScript variables out of a string of html?>

I've retrieved some JavaScript that basically looks like the following. That is, I have it in a const as is below. without writing a bunch of ugly parsing looking for variables, is there a clever way to get the values of traffic_days, traffic_day_persent,traffic-mbytes, etc.?

const htmlData = `
 <html>
  <body bgcolor="#ffffff">
    <form method="POST" action="/apply.cgi">
      <div id="main" class="main">
        <script>
          var traffic_days = "13/31";
          var traffic_day_persent = "41";
          var traffic_mbytes = "57346.86/1000000  Mbytes ";
          var traffic_mbytes_persent = "5";
          var warning_value = "";
          if (timereset == "") timereset = "5";
        </script>
      </div>
    </form>
    <script>
      alert('testing');
    </script>
  </body>
 </html>`;

Upvotes: 0

Views: 154

Answers (2)

Sarandi
Sarandi

Reputation: 19

I'm unaware of solutions that use cleverness without providing something/pattern to parse.

Assuming that any variable value between quotes is valid, just swap out the variable name and the ".+" bit stays the same:

var trafficDays = htmlData.match('traffic_days = ".+"')[0];

var trafficMbytes = htmlData.match('traffic_mbytes = ".+"')[0]; etc.

Those don't look that ugly to me. Sorry if this isn't what you're looking for (I don't have the rep to ask questions yet).

I tested this using Node's REPL:

$ node
> const htmlData = `
...  <html>
...   <body bgcolor="#ffffff">
...     <form method="POST" action="/apply.cgi">
...       <div id="main" class="main">
...         <script>
...           var traffic_days = "13/31";
...           var traffic_day_persent = "41";
...           var traffic_mbytes = "57346.86/1000000  Mbytes ";
...           var traffic_mbytes_persent = "5";
...           var warning_value = "";
...           if (timereset == "") timereset = "5";
...         </script>
...       </div>
...     </form>
...     <script>
...       alert('testing');
...     </script>
...   </body>
...  </html>`;
undefined
> var trafficDays = htmlData.match('traffic_days = ".+"')[0];
undefined
> console.log(trafficDays);
traffic_days = "13/31"

Upvotes: 2

Timothy Lee
Timothy Lee

Reputation: 828

This is a fast but tricky way to do:

replace the characters that are not number and calculators, then use eval

const traffic_mbytes = "57346.86/1000000  Mbytes "
const traffic_mbytes_string = traffic_days.replace(/[^\d/]/g, '')
// become "5734686/1000000", then you can use eval
const result = eval(traffic_mbytes_string)
// 5.734686

of course, if the string might contain +, -, * or some other calculators, your regular expression should change to /[^\d/+-*]/.

Also, some special cases for example: 13/31 Some/text will go wrong, so you need to adjust your regexp depend on possible string patterns.

Upvotes: 0

Related Questions