Display first and last names first letters in a div with only one input in JavaScript

I am trying to create a text input where you can write your first name and your last name. The first letter of the first name and surname should be displayed in a DIV. The letters should be displayed directly without clicking a button.

For example:

You write "John Doe" in the text field and JD should be displayed in the DIV.

In the end it should look like this:
In the end it should look like this

18 thoughts on “Display first and last names first letters in a div with only one input in JavaScript”

  1. const extractFirstLetters = function(name) {
      let firstName = name.split(' ')[0];
      let lastName = name.split(' ')[1];
      let firstLetters = firstName[0] + lastName[0];
      return firstLetters;
    let output = extractFirstLetters("John Doe")
    // Output => "JD"

    Proceed to set div.innerHTML = output.

    More on JS DOM Methods.

  2. There are two ways to achieve this:-

    1 – Text way

    const val = document.getElementById('name').value;
    document.getElementById('initials').innerHTML = val.split[" "][0] + val.split[" "][1]
    <div id="initials"><div>
    <input type="text" id="name" value="John Doe">

    2 – Image way

    Using API to generate an image of the initials,


    And set the image as the background of the initials div.

  3. Try something like this:

    let text = ''
    document.querySelector("input").addEventListener("input", () => {
      text = document.querySelector("input").value;
      let full_name = text.split(" ");
      let initials = full_name[0][0];
      if (text) {
        if (full_name.length >= 2 && full_name[1]) {
          initials += full_name[1][0];
      } else {
        initials = '';
      document.querySelector("div").innerHTML = initials;
    <!DOCTYPE html>
    <html lang="en">
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <input type="text">

Leave a Comment