Ad

Javascript Substring() Returning The Wrong Value From My String?

- 1 answer

I have this code:

var sequence = $stateParams.testId.length == 14 ?
               parseInt($stateParams.testId.substring(11, 2)) : 0;

What I expect is for the sequence to be set to 01 (the last two numbers). But what happens is that it returns 198.

Can someone explain why this is?

console.log($stateParams.testId) // "01198-05282-01"

console.log(sequence) // 198

Ad

Answer

String#substring works with the indexes.

The signature of the substring is

str.substring(indexStart[, indexEnd])

Note that the second parameter is the index itself and not the length of the substring.

Quoting from MDN

If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).

So,

.substring(11, 2) is equivalent to .substring(11, 2) which will give the substring "198-05282-" and using parseInt() on it will give the output as 198.

  1. Use the second param as index, here, 14(12 + 2)
  2. Use the radix parameter to parseInt as 10 to avoid unexpected results

Code:

var str = '01198-05282-01';

var sequence = str.length == 14 ?
    parseInt(str.substring(12, 14), 10) : 0;
//                             ^^   ^^

console.log(sequence);

To get the substring using the length, use String#substr

str.substr(12, 2)
Ad
source: stackoverflow.com
Ad