How to trim a string of whitespace using a function in JavaScript

Following is a custom JavaScript function which will trim whitespace characters from your string variable. This function can also be used in your validation functions to check whether the user has deliberately entered whitespace characters or not.

function trimstr(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;
}

var str = 'Ronald  ';

// Will display alert box with 8
alert(str.length);

str = trimstr(str);

// Will display alert box with 6
alert(str.length);
Please follow and like us:

Be the first to comment

Leave a Reply

Your email address will not be published.


*