I want to override parseInt to remove commas first

Running in tampermonkey on chrome

Ie rather than parseInt(s)

It will do

s.replace(/,/g, '');
parseInt(s)

My current code is

(function() {
    // log all calls to setArray
    var proxied = parseInt;
    parseInt = function() {
        arguments[0]=arguments[0].replace(/,/g, '');
        return proxied.apply( this, arguments );
    };
})();

I get error "arguments[0].replace is not a function"

2 Answers

0
Nicolas On Best Solutions

You should be sure your argument is a String :

(function() {
    // log all calls to setArray
    var proxied = parseInt;
    parseInt = function() {
        arguments[0]=arguments[0].toString().replace(/,/g, '');
        return proxied.apply( this, arguments );
    };
})();

EDIT : This solution is better than casting I think because of the definition of the first argument of parseInt:

The value to parse. If the string argument is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string argument is ignored.

EDIT2 : As it's been said in comments: it's not really a good practice. However, if still want to do this, you should also allow the second argument (base)

0
Jjagwe Dennis On

Its because you passed it a number. One possible solution can be casting arguments[0] to a string before calling the replace method on it like

(function() {
    // log all calls to setArray
    var proxied = parseInt;
    parseInt = function() {
        arguments[0]=String(arguments[0]).replace(/,/g, '');
        return proxied.apply( this, arguments );
    };
})();