-5

Can you tell me if it is ok to use string functions on numbers in Javascript? I have a code which needs to do some modifications on string values. Like here:

var value = 0;

if( tableRow.find('input').length )
{
    value = tableRow.find('input').val();
}

value = value.replace(/\s/g, '')  // Remove spaces

But sometimes value before replace() remains default 0 which is number type. So is it ok to call replace( or other string function ) on the number? It seems it works but I am not sure if all browsers will support it.

EDIT: Not it is not possible. My code works fine because it is always string and condition is not skipped. But variables of number type have NOT .string() function.

Čamo
  • 3,863
  • 13
  • 62
  • 114

3 Answers3

3

You can't call replace on a number. What you can do is to call it on value.toString() or to set value initially to 0

Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
Programmer
  • 1,973
  • 1
  • 12
  • 20
  • 1
    Yes you are right. Numbers has no .string() function. My code works cause it is always string and conditions is not skipped in my case. – Čamo Jul 25 '18 at 08:37
3

Is it possible to use string functions on numbers in javascript?

No. Numbers and strings have different methods. Numbers don't have a replace method (because it doesn't make sense for numbers, but does make sense for strings).

But sometimes value before replace() remains default 0 which is number type.

To avoid that, make your default a string as well:

var value = "0";
// ---------^-^

if( tableRow.find('input').length )
{
    value = tableRow.find('input').val();
}

value = value.replace(/\s/g, '')  // Remove spaces

...or only do the replace on the other path, and convert to number on the other path:

var value = 0;

if( tableRow.find('input').length )
{
    value = tableRow.find('input').val();
    value = +value.replace(/\s/g, '')  // Remove spaces, convert to number
}

(+ is just one way to convert to number. You have several options, each with pros and cons.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

No, it's not possible to use replace on numbers, because there is not such function in the Number class.

Your value propably is a string, (check it with typeof(value) ), that string containing only numbers don't make it a number.

value = 10 it's not the same as value = "10".