Live Chat Icon For mobile
Live Chat Icon

Is there Trim function available in Javascript?

Platform: ASP.NET| Category: Client Side Scripting

There is no predefined trim function available. The function written below is used to Trim white spaces.


//Trim Function
function LTrim(str)
{
	var whitespace = new String(' \t\n\r');
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1)
	{
		var j=0, i = s.length;
	 	while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
		j++;
		s = s.substring(j, i);
    	}
	return s;
}

function RTrim(str)
{
	var whitespace = new String(' \t\n\r');
	var s = new String(str);
	 if (whitespace.indexOf(s.charAt(s.length-1)) != -1) 
	 {
		var i = s.length - 1;      
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
		i--;
		s = s.substring(0, i+1);
	 }
	 return s;
}

function Trim(str)
{
	return RTrim(LTrim(str));
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.