How to trim a string in JavaScript?

1. Using a function

function trim(s) {
	return s.replace(/^\s+|\s+$/g, '');
}
 
s = "    Hello World    ";
( trim(s) == "Hello World" ); // true

2. Augmenting the String prototype

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};
 
s = "    Hello World    ";
( s.trim() == "Hello World" ); // true

3. If you are using jQuery

s = "    Hello World    ";
( $.trim(s) == "Hello World" ); // true
Both comments and pings are currently closed.

Comments are closed.