Trim Function In Javascript

March 20th, 2008 | by programming |

There is no trim() function in javascript, but it’s very easy to implement:

var regExpBeginning = /^\s+/;
var regExpEnd = /\s+$/;

// Remove whitespaces from the beginning and the end of the string.
function trim(aString) {
return aString.replace(regExpBeginning, “”).replace(regExpEnd, “”);
}

// Remove whitespaces from the beginning of the string.
function ltrim(aString) {
return aString.replace(regExpBeginning, “”);
}

// Remove whitespaces from the end of the string.
function rtrim(aString) {
return aString.replace(regExpEnd, “”);
}

Post a Comment