PDA

View Full Version : remove leading and trailing spaces


ventura
08-07-2003, 05:33 PM
i got this script from dreamweaver but can't figure out how to implement it in a text field.

i was using:
onChange="return removeLeadingAndTrailingChar(this.value,' ');"

but it doesn't seem to work.


function removeLeadingAndTrailingChar(inputString, removeChar) {
var returnString = inputString;
if (removeChar.length) {
while('' + returnString.charAt(0) == removeChar) {
returnString = returnString.substring(1,returnString.length);
}
while('' + returnString.charAt(returnString.length-1) == removeChar) {
returnString = returnString.substring(0,returnString.length-1);
}
}
return returnString;
}

Vladdy
08-07-2003, 05:54 PM
function trim(string)
{ return string.replace(/^\s*(.*)\s*$/,'$1');
}

harness the power of Regular Expressions!!!

onchange = "this.value = trim(this.value);"

Choopernickel
08-07-2003, 06:15 PM
METHODS.

String.prototype.Ltrim = function () {
var whitespace = new RegExp("^\\s+","gm");
return this.replace(whitespace, "");
}

String.prototype.Rtrim = function () {
var whitespace = new RegExp("\\s+$","gm");
return this.replace(whitespace, "");
}

String.prototype.Trim = function () {
return this.Rtrim().Ltrim();
}
String.prototype.Trim = Trim;


Use like this:

" padLeft".Ltrim(); // returns value "padLeft" (no quotes)
"padRight ".Rtrim(); // returns value "padRight"
" padded ".Trim(); // returns value "padded"