JavaScript doesn’t have a built-in Trim function, which trims white spaces from the beginning and the end of a string. In this article I’ll show you how to create 3 very useful trim JavaScript functions – leftTrim(), rightTrim(), and allTrim().
Lets start with leftTrim() function, which will trim all white spaces in front of a string and will return the trimmed string. Please have a look at the leftTrim JavaScript function below:
function leftTrim(sString)
{
while (sString.substring(0,1) == ' ')
{
sString = sString.substring(1, sString.length);
}
return sString;
}
The leftTrim JavaScript function takes one parameter, which is the string that needs to be trimmed. The function then loops through each of the characters of this string, starting with the first one. If the current character in the loop is a single white space “ “, the function removes it from the string and continues with the loop. The loop goes on until it finds character, which is different than a single white space or until it reaches the end of the string. After the function exits the loop, it returns the left trimmed string.
The rightTrim() JavaScript function works in exactly the same way, except that it trims the white spaces at the end of the string:
function rightTrim(sString)
{
while (sString.substring(sString.length-1, sString.length) == ' ')
{
sString = sString.substring(0,sString.length-1);
}
return sString;
}
The allTrim() JavaScript function combines both leftTrim() and rightTrim() functions:
function trimAll(sString)
{
while (sString.substring(0,1) == ' ')
{
sString = sString.substring(1, sString.length);
}
while (sString.substring(sString.length-1, sString.length) == ' ')
{
sString = sString.substring(0,sString.length-1);
}
return sString;
|