Documentation and Books

Recent site activity

Web Development‎ > ‎JavaScript‎ > ‎

How to do a trim() operation on a String?

The following is a very nice solution to perform a trim() function on a String, it uses the prototype functionality to add a method trim to the String class:

  <script type="text/javascript">

String.prototype.trim=trim;

function trim() {
return this.replace(/^\s+|\s+$/g,'');
}

</script>

You can use this new function in the following way:

  <script type="text/javascript">

var text = " HELLO ";
alert(text.trim());

</script>