Skip to content
Advertisement

Keeping zero value in reverse string javascript

I would like to reverse a string in javascript and keep zero value.

function reverseNumb(a) {
  let reverse = Array.from(String(a),Number).reverse();
    return Number(reverse.join(''));
}

reverseNumb(01234567);

It keeps on removing the 0 and if you add 0 it gives a totally different number

Would like it to keep the number zero and not change the value to something different wen adding the number 0

Any help would be appreciated

Advertisement

Answer

When you are looking at a Number data type, if it has a leading zero that zero is disregarded as being meaningless. If you are talking about a base 10 number system, and not binary or octal or hex or whatever else, 0100, or even 000000100 are both just equal to 100. So the number, 01234567 is rightly read and stored as a Number as 1234567.


EDIT: Just to be clear here, in the actual code if you are not explicit that you are in base 10, a leading 0 will cause the number to be read and stored as an octal value (or a hex value if the leading 0 is followed by an x) in some operations. So the statement, let num = 0100 results in num being saved with the value of 64 in loose mode and a SyntaxError being thrown in Strict Mode. However, parseInt("0100", 10), Number("0100"), "0100"|0, and +"0100" are all equal to 100.


If you want to keep a leading zero, you would be better served representing the data as a String, which you can do simply by wrapping it in quotation marks: reverseNums("01234567"). If you need to have the function return numbers that also contain leading zeros you will need to return a string, which you can do by simply not casting it to a number in your return statement: return rev.join('')

However, since you are now using a string as input, you can write a more simple string reversal function by using the split method from the String object to first convert your input into an Array, and then chaining the rest of your methods after that, like this:

function reverseString(str) {
  return str.split('').reverse().join('');
}

You could also write a string reversal function using the modern, less verbose, ES6+ syntax by using an arrow function expression like this:

const reverseString = str => str.split('').reverse().join('');
Advertisement