1

I'm not guru of javascript, so don't blame me much. My task is to find and replace text inside html page, so every number should be replaced with it's value multiplied by some amount. e.g. 123 -> 104.55(123*0.85), 245 -> 208,25(245*0.85) etc. Currently my code is like following:

$('body').html(
      $('body').html().replace(/([0-9\.]+)/g, eval("$1*0.85"))
);

eval("$1*0.85") return NaN while trying parseFloat($1)*0.85 also does not return correct results Can someone advise? Thanks.

zergussino
  • 821
  • 11
  • 14

2 Answers2

3

You probably don't want to take the whole page's HTML and replace it with updated HTML, because all of the elements get torn down and recreated, which has implications for event handlers and the like.

It happens that just yesterday I answered this other question here. The answer can be applied quite easily to your situation.

Update: Since you're not moving the result into a new element, the code actually gets simpler:

walk(document.body);

function walk(node) {
  var child;

  switch (node.nodeType) {
    case 1: // Element
      for (child = node.firstChild;
           child;
           child = child.nextSibling) {
        walk(child);
      }
      break;

    case 3: // Text node
      node.nodeValue = node.nodeValue.replace(
        /[0-9]+(?:\.[0-9]+){0,1}/g,
        function($0) {
          msgs.push($0);
          var num = parseFloat($0, 10);
          if (isNaN(num)) {
            return $0;
          }
          return num * 0.85;
        }
      );
      break;
  }
}

Live example

Note that I've modified the regexp a bit, you might want to massage it until it's how you want it. But I wanted to match decimal points only when followed by digits. (It's worth noting that not all cultures use . as the decimal point, but you seemed to in your example, so...)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @zergussino: I took a first stab at it; enough to get you going, anyway, and it works with the test data I threw at it. – T.J. Crowder Mar 02 '11 at 09:07
2

it should be sth like this,

var x = $('body').html();

x = x.replace(/([0-9.]+)/g, function ( x ){ return x*0.85;});

$('body').html(x);

if you do not consider events, etc

Zer001
  • 619
  • 2
  • 8
  • 18
  • 2
    @zergussino: That will work, yes, but again beware that you may mess up event handlers by completely tearing down and rebuilding the page. Using `html()` on the `body` element is a big hammer. – T.J. Crowder Mar 02 '11 at 10:56
  • @T.J. Crowder I agree, giving you a + – Zer001 Mar 03 '11 at 04:09
  • @T.J. Crowder Yes I'm aware of that issue. The only thing I needed is some head-ups. Modified above code to my needs. Thanks everybody for help – zergussino Apr 26 '11 at 00:54