How to slice a number in JavaScript?

Viewed 11651

I've the following code snippet,

var code = 895804220010013030;
var last = code.slice(-2);
var n = last.includes(00, 01, 10, 11, 20, 21, 30, 31 );

if (n===true) {
  alert(n)
} else {
 alert('false')
}

But it invokes syntax error, the only way it works well is to put the quotes to the numbers

var code = 895804220010013030;

but I need to run it without putting the quotes.

3 Answers

change this :

var last = code.slice(-2);

to this :

var last = String(code).slice(-2);

or this :

var last = code.toString().slice(-2);

WHY?

because slice() is method of String not a Number. It extracts a section of a string and returns it as a new string, without modifying the original string.

UPDATE

based on the first comment.

var code = 130031;
var last = code.toString().slice(-2);
var n = [00, 01, 10, 11, 20, 21, 30, 31].includes(last);

For more information read about includes

EDIT:

Have to edit the start of the answer since I just realized that the number you're trying to capture in the code variable is actually greater than the max safe integer value available in JS.

slice is not a method defined on the Number type. You can choose to store the code as a string and that will make life easier for you,

var code = '895804220010013030';
var last = Number(code.slice(-2));
var n = [00, 01, 10, 11, 20, 21, 30, 31].includes(last);

if (n===true) {
  alert(n)
} else{
 alert('false')
}

Additionally, there are better ways to write the if-else since the value of n is going to be a boolean as includes will always return a true or false.

From MDN,

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

Either,

if (n) {
  alert(n);
} else {
  alert(false);
}

or simply,

alert(n);
Related