DEV Community

Morris John
Morris John

Posted on

How do I get the first/last char of a string from a user input (input.value)

So I'm trying to build this project where I ask the user to enter their name, then I display said name in full and put the initials in a button instead of "player one". I don't know why but slice(-1), charAt(str.length -1) are not working.

<div>
        <label for="name">Enter your name</label>
        <input type="text" name="" id="yn">
        <button class="submit">Submit</button>
    </div>
    <p class="welcome"></p>
Enter fullscreen mode Exit fullscreen mode
var yourname = document.querySelector("#yn");
var welcome = document.querySelector(".welcome");
var div = document.querySelector("div");
var submit = document.querySelector(".submit");

submit.addEventListener("click", function(){
    div.classList.add("hide");
    welcome.textContent = "Welcome " + yourName.value
})
Enter fullscreen mode Exit fullscreen mode

Thanks

Top comments (4)

Collapse
 
donnii profile image
Daniel Dark • Edited

There's a typo

wrong:

var yournmae = document.querySelector("#yn");

correct:

var yourName = document.querySelector("#yn");
Collapse
 
morrisjohn profile image
Morris John

Okay thanks. I've corrected it

Collapse
 
donnii profile image
Daniel Dark

And here is what you want:

submit.addEventListener('click', () => {

    const {value} = yourName

    const firstChar = value.slice(0, 1)
    const lastChar = value.slice(-1)

    div.classList.add('hide')
    welcome.textContent = firstChar + lastChar
})
Thread Thread
 
morrisjohn profile image
Morris John • Edited

Wow, that worked.

I don't even understand the code (*LOL I haven't learnt the 'const / {} => yet *) but yeah it worked.

Thank you very much