Doubt about indexOf () in string

0

please if you could give me more detail of why the return of each exercise:

"Blue Whale".indexOf("Whale",0) // returns 5

"Blue Whale".indexOf("Whale",5) // returns 5

"Blue Whale".indexOf("",9)      // returns 9

Thank you.

    
asked by user889 21.03.2018 в 03:52
source

1 answer

3
  • The first one returns you 5 because it reads the text string as an array of positions where you tell it to start from position 0 and find that the word Whale starts at position 5
  • The second returns you 5 because it finds that the first match of the text string you declare starts at position 5
  • The third returns you to nine because in the function you are indicating that you find from position nine the first match that has no strings, numbers, or blanks and just in that position is where your chain ends of text and has some quotation marks with no space, that's why you return nine because if you find a match
  •   

    The indexOf method reads everything as a position is number, space in   white or string of text

    Here the example with each of the scenarios proposed in the question

    let phrase = 'Blue Whale'
    
    console.log(phrase.indexOf("Whale", 0))
    
    console.log(phrase.indexOf("Whale", 5))
    
    console.log(phrase.indexOf("", 9))

    the indexOf() method when reading the text text as an array; it's as if I saw it in the following way

    B L U E   W H A L E  => CADENA DE TEXTO
    0 1 2 3 4 5 6 7 8 9  => POSICIÓN DENTRO DEL ARRAY DE CADA ELEMENTO
    
        
    answered by 21.03.2018 в 04:14