JavaScript to grab the left or right characters from a string


Useful any time you want to know what the first N characters or last N characters of a string are.

For example, if you have a code that is made up of two parts like "ABCD-12345" and you need to break it into "ABCD" or "12345", you can use these functions.

String to parse:

Length of text to grab:

Show me what is on the left

Show me what is on the right

function Left(str, n){

  if (n <= 0)

    return "";

  else if (n > String(str).length)

    return str;

  else

    return String(str).substring(0,n);

}

function Right(str, n){

  if (n <= 0)

    return "";

  else if (n > String(str).length)

    return str;

  else {

    var iLen = String(str).length;

    return String(str).substring(iLen, iLen - n);

  }

}