Javascript string property does not have the normal trim functions like we have in any other language. And these trim functions appears play a crucial role in any code based on strings. There are two approaches i give here. One is directly creating a prototype method and other as a standalone function. You can choose the one depending on your needs.
Trim functions on the string prototype:
String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,””);}String.prototype.ltrim = function() {return this.replace(/^\s+/,””);}String.prototype.rtrim = function() {return this.replace(/\s+$/,””);}// example of using trim, ltrim, and rtrimvar myString = ” hello my name is “;alert(“*”+myString.trim()+”*”);alert(“*”+myString.ltrim()+”*”);alert(“*”+myString.rtrim()+”*”);
Trim functions as a standalone:
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,””);
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,””);
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,””);
}
// example of using trim, ltrim, and rtrim
var myString = ” hello my name is “;
alert(“*”+trim(myString)+”*”);
alert(“*”+ltrim(myString)+”*”);
alert(“*”+rtrim(myString)+”*”);
Hope this helps.