Two functions for trim() in javascript

Trim is one of the most common operations in any programming language. That's while it is implemented in almost all of them. I was amazaed that javascript doesn't provide this. Here are two functions for that purpose.

1. Using cycles

function trim(str)
{
if (str=="")
return "";
while (str.indexOf(" ")==0)
{
str = str.substring(1,str.length);
if (str=="")
return "";
}
while (str.lastIndexOf(" ")==(str.length-1))
{
str = str.substring(0,str.length-1);
if (str=="")
return "";
} return str; }

2. Using RegEx

function trim(str)
{
return str.replace(/^\s*|\s*$/g,"");
}

 

No comments yet

Back to articles list

This page was last modified on 2018-12-09 01:27:57