Search code examples
javascriptloopsfor-looptddslice

Having some problems understanding why its not slicing my string


describe('China UnionPay', function() {
  let expect = chai.expect;

  for (var prefix = 624; prefix <= 626; prefix++) {
    for (let j = 17; j <= 19; j++) {
      let cardNum = `${prefix}7891123456789`;
      (function(prefix) {
        it(`it has a prefix of ${prefix} and a length of ${j}`, function() {
          //  console.log(`${cardNum.slice(0,j)}`)
          console.log('typeof cardNum', typeof cardNum, '    ', 'length of string =>', j, 'card is not the length of j?', cardNum.slice(0, j))

          expect(detectNetwork(cardNum.slice(0, j))).to.equal('China UnionPay');
        })
      })(prefix)
    }
  }
})

What I would like this code to do is to take the cardNum and slice from 0 to the length of what j is currently at. I already added the prefix to the front but not sure why it's not returning a slice portion of cardNum and returning the whole thing?


Solution

  • Value of j in your code ranges between 17 and 19. While length of your string i.e. var cardNum is 13 characters + 3 characters of var prefix. So basically length of your resulting cardNum variable is 16. Syntax of slice function is str_name.slice(startPointPosition, endPointPosition); And in the code above endPointPosition i.e. value of var j is always greater than total length of cardNum. If you change value of j to less than 16 you can see the change.