javascriptlastindexof

really simple question about why lastIndexOf() returns -1 in this case


i have this piece of string and i want to get the last index of "n" in it but instead of returning 200+ or something it returns -1. which i did not find it . why is that ?

s="2\n8\n6\n2\n12\n3\n4\n11\n1\n1\n11\n9\n1\n14\n8\n9\n2\n5\n5\n12\n6\n0\n10\n0\n0\n6\n6\n8\n0\n11\n14\n12\n12\n9\n13\n12\n0\n4\n14\n5\n11\n10\n14\n1\n6\n6\n5\n0\n4\n3\n8\n8\n12\n13\n4\n7\n2\n7\n1\n2\n9\n4\n5\n11\n12\n11\n11\n8\n11\n5\n6\n12\n13\n7\n11\n10\n10\n12\n11\n13\n14\n11\n3\n10\n3\n8\n7\n14\n12\n14\n8\n7\n14\n11\n8\n14\n10\n6\n12\n7"
console.log(s.lastIndexOf("n"))


Solution

  • None of the characters in the string are literal n characters - rather, you're using \n, which is the escape sequence for a newline character, eg

    const str = `
    `;
    

    is a string composed of a newline character, which is equivalent to

    const str = '\n';
    

    If you wanted your string to be composed of literal backslashes and literal ns, use String.raw to disable escape sequences.

    const s = String.raw`2\n8\n6\n2\n12\n3\n4\n11\n1\n1\n11\n9\n1\n14\n8\n9\n2\n5\n5\n12\n6\n0\n10\n0\n0\n6\n6\n8\n0\n11\n14\n12\n12\n9\n13\n12\n0\n4\n14\n5\n11\n10\n14\n1\n6\n6\n5\n0\n4\n3\n8\n8\n12\n13\n4\n7\n2\n7\n1\n2\n9\n4\n5\n11\n12\n11\n11\n8\n11\n5\n6\n12\n13\n7\n11\n10\n10\n12\n11\n13\n14\n11\n3\n10\n3\n8\n7\n14\n12\n14\n8\n7\n14\n11\n8\n14\n10\n6\n12\n7`;
    console.log(s.lastIndexOf('n'))

    If you want the string to be composed of newline characters, and you want to check the last index of a newline character, pass a newline character into lastIndexOf.

    s="2\n8\n6\n2\n12\n3\n4\n11\n1\n1\n11\n9\n1\n14\n8\n9\n2\n5\n5\n12\n6\n0\n10\n0\n0\n6\n6\n8\n0\n11\n14\n12\n12\n9\n13\n12\n0\n4\n14\n5\n11\n10\n14\n1\n6\n6\n5\n0\n4\n3\n8\n8\n12\n13\n4\n7\n2\n7\n1\n2\n9\n4\n5\n11\n12\n11\n11\n8\n11\n5\n6\n12\n13\n7\n11\n10\n10\n12\n11\n13\n14\n11\n3\n10\n3\n8\n7\n14\n12\n14\n8\n7\n14\n11\n8\n14\n10\n6\n12\n7"
    console.log(s.lastIndexOf("\n"))