Search code examples
jqueryif-statementstring-length

Trying to get the first 5 characters of input 1, and first character of input 2


I am trying to generate usernames for users based on the exisiting manual formula we use: first 5 characters of last name, first initial of first name.

Simple:

$("#first_name, #last_name").keyup(function(){
    var a = $("#first_name").val().substring(0, 1),
        b = $("#last_name").val().substring(0, 5);

    $("#username").val(b+a);
});

However, I have been trying to figure out the rules for when the last name is less than 5 characters, and then fill those missing characters with the next letters of their first name. And lastly if the first + last name is less than 5 characters in total, just add them.

This was something along the lines I was working towards, but it wasn't working and I can't seem to logic why:

$("#first_name, #last_name").keyup(function(){

    var a = $("#first_name").val(),
        b = $("#last_name").val();

    if( b < 5 ) {

        var c = ( 5 - b.length );

        if( c > a.length ) {
            var d = a.substring(0, c);
            $("#username").val( b + d );
        } else {

            $("#username").val( b + a );
        }

    } else {

        $("#username").val( b + a );

    }       
});

Solution

  • I have been trying to figure out the rules...

    The key here is the last name. You have only 2 cases, and it depends on the last name length.

    When you know it is less than 5 chars. Use it as is!
    And use it's length to calculate how many chars to use from the first name.

    $("#first_name, #last_name").keyup(function(){
    
      var a = $("#first_name").val(),
          b = $("#last_name").val();
    
      // Last name longer than 5 chars
      if( b.length >= 5 ) {
        a = a.substr(0,1);
        b = b.substr(0,5);
        
      // Last name shorter than 5 chars
      }else{
        a = a.substr(0,(5-b.length+1));  // That is at least 1 + 5 possible "replacements"...
      }
    
      $("#username").val( b + a );
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    First name: <input type="text" id="first_name"><br/>
    Last name:  <input type="text" id="last_name"><br>
    username: <input "type="text" id="username">