0

I am running into an error in IE 9 and 10. The error is "Unable to get property 'replace' of undefined or null reference". If we are to believe Microsoft's error, it reports the error is occurring on the value.replace line of the following function:

function jsstrtonum($value) {
    if($value == '') {
        $value = '0.00';
    }
    var $retval = $value.replace(/[^0-9\.]+/g, '');

    return Number($retval);
}

I am only having difficulty in IE. All other browsers execute this function flawlessly. I have been working on this for hours now. Any help would be greatly appreciated.

bnorton
  • 43
  • 2
  • 2
  • 4
  • 3
    Are you sure `$value` is always a string? – gen_Eric Dec 28 '12 at 22:34
  • 1
    as Rocket said, it may be because $value is null, or not a string. I would convert $value to a string before hand: $value = $value + ""; – kennypu Dec 28 '12 at 22:37
  • 2
    Do you intend to put 0.00 in the string and then replace it with an empty string on the next line? It will take out all the digits and dots you just put there when the regex finds them. – Lee Meador Dec 28 '12 at 22:43
  • @LeeMeador, note the negation operator (`^`), the intention is just the opposite. – Eliran Malka Dec 28 '12 at 22:51
  • can't reproduce, using IENetRenderer for IE9. please create a demo test that can reproduce this issue, including examples of passed values (you can use [jsFiddle](http://www.jsfiddle.net) for that). – Eliran Malka Dec 28 '12 at 23:04

3 Answers3

0

try

$value = new String($value);

before using 'replace'.

algorhythm
  • 8,530
  • 3
  • 35
  • 47
  • 3
    I would suggest `$value = ''+$value` instead. That returns a `String` object, which doesn't *always* act the same as a "primitive" `string`. See: http://stackoverflow.com/q/5750656 – gen_Eric Dec 28 '12 at 22:39
  • @RocketHazmat yeah, good point. the problem is just to ensure, that the given parameter is a string. i think, in this case, both is a solution. – algorhythm Dec 28 '12 at 22:48
  • Thank you. This works. I am running into another issue that is throwing the same error. I may have to post that one too. Thank you for your help. It would be a whole lot easier if everyone just didn't use IE. – bnorton Dec 29 '12 at 16:26
0

As Rocket Hazmat suggested, the problem is most likely that $value is something other than a string. One quick and dirty approach you could use to debug what it is is:

function jsstrtonum($value) {
    if (!$value.replace) {
        alert($value);
        // Alternatively if the IE developer tool gives you a console you could:
        // console.log($value);
    }
}

This way you can see what $value is, and hopefully debug your problem from there.

machineghost
  • 33,529
  • 30
  • 159
  • 234
0

Might as well just replace the condition with:

if (!$value)

So that all the nulls and undefined values turn into the 0.00 string.

Lee Meador
  • 12,829
  • 2
  • 36
  • 42