Search code examples
javascriptjquerysubstringsubstr

Different outcome of substr() when using variable vs getting input value


I have some javascript that I'm using in a few places to check the last 3 characters of an email address. What I don't understand is why I get different outcomes when I'm getting the substring of a set variable vs when I grab the input value.

The code below will alert with value: "com"

var email = "blah@test.com";
alert(email.toLowerCase().substr(email.length - 3, 3));

However, this code that grabs the input value alerts with a value: "om"

alert($("#email").val().toLowerCase().substr($("#email").length - 3, 3));

Can anyone explain to me why the above two lines of code have different outcomes?

Here is a JSFIDDLE


Solution

  • Try to pass the length of the value of the text box, not the length of selected elements,

    alert($("#email").val().toLowerCase().substr($("#email").val().length - 3, 3));
    //-------------------------------------------------------^^^^^
    

    And the best approach for accomplishing this would be,

    var value = $("#email").val().toLowerCase();
    alert(value.substr(-3)); 
    

    Passing start value in negative will strip the string from the behind.

    DEMO