Skip to main content

Trim method in JavaScript

· One min read
Sandeep Bhardwaj

We can use String.replace method to trim a string in javascript.

//method for trim a complete string like "  Hello World   "  
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}

//method for left trim a string like " Hello World"
function leftTrim(str) {
return str.replace(/^\s+/,"");
}

//method for right trim a string like "Hello World "
function rightTrim(str) {
return str.replace(/\s+$/,"");
}