Documentation and Books

Recent site activity

Web Development‎ > ‎JavaScript‎ > ‎

How to remove all leading whitespaces in a String?

The following is a very nice solution to remove all leading white spaces in a String, it uses the prototype functionality to add a method trimLeading to the String class:

  <script type="text/javascript">

String.prototype.trimLeading=trimLeading;

function trimLeading() {
return this.replace(/^\s+/,'');
}

</script>

You can use this new function in the following way:

  <script type="text/javascript">

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

</script>