-2

I have some exercises that are a little ambiguous: I have to find the first index of any name that is defined inside a prompt(), but the problem is that using indexOf() I must define a letter to start the search.

Is there an efficient way to define what would be the first and last letter of variable names that have not been explained to me in the course?

const name = prompt('please, type your name here);


document.body.innerHTML += `What's the first letter of your name? ${name.indexOf(0)}<br />`;
document.body.innerHTML += `What's the last letter of your name? ${name.lastIndexOf(-1)}<br />`;

Edit: I ended up finding a .CHM document that contained JS instructions, and in it I discovered the Slice() method, I ended up finding a solution for the first letter, but how could I always choose the last letter of any name within a variable?

Answer for the first letter:

document.body.innerHTML += `What's the first letter of your name ${name.slice(0, 1)}<br />`;
Kazbonfim
  • 11
  • 4
  • 1
    if you want the first char of a string you can do name[0], last char is name[name.length-1] – Chris Li Jul 17 '22 at 02:32
  • indexOf is used to find the index of letters in a string it returns a number In your case you could use name[0] for the first letter and name[name.length-1] for the last letter – Mohamed EL-Gendy Jul 17 '22 at 02:39
  • Muito Obrigado! Sound's like 'thanks you guys, you're blessed!' I've found that Slice() method does this too, but for some reason my teacher didn't mention that earlier. Now, how the hell i can find always the last letter, without defining a name in mind, but contained within a variable and that can be anything? – Kazbonfim Jul 17 '22 at 02:55

1 Answers1

-1

you can using "indexing", like this:

name[0] //first letter
name[name.length-1] //last letter, remember that js sequences are 0 indexed
Ghazi
  • 583
  • 5
  • 20