Trim in JavaScript

In JavaScript, there is no trim method. But below i have created a simple trim method which removes the leading and the trailing spaces from the string.

function trim(str) {

str = str.replace(/^s+/, '')

for (var i = str.length; i--; )

 if (/S/.test(str.charAt(i)))

            return str.substring(0, ++i)

        return str

 }

 function testTrim() {

     var myString = " Test Trim ";

     alert(trim(myString));

}

Ebook Download
View all
Learn
View all