In this article I will explain with an example, how to remove White Space from beginning (start) and end of string using JavaScript.
When the Remove Button is clicked, a JavaScript function is called and the whitespace is removed from beginning (start) and end of the TextBox value using JavaScript.
 
 
HTML Markup
The following HTML Markup consists of an HTML TextBox and a Button. The Button has been assigned with an OnClick event handler.
<input type="text" id="txtName" value=" MUDASSAR KHAN " />
<input type="button" id="btnRemove" value="Remove Whitespace" onclick="RemoveWhitespace()" />
 
 
JavaScript Code
When the Remove Button is clicked, the RemoveWhitespace JavaScript function is called.
Inside the function, first the TextBox is referenced and then the whitespace is removed from beginning (start) and end of the string using the JavaScript trim function.
Note: The function trim is an inbuilt JavaScript function and is supported in all Modern browsers.
 
Finally, the updated string value is re-assigned to the TextBox.
<script type="text/javascript">
    function RemoveWhitespace() {
        var txtName = document.getElementById("txtName");
        txtName.value = txtName.value.trim();
    };
</script>
 
 
Screenshot
JavaScript: Remove whitespace from Beginning (Start) and End of String
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Demo
 
 
Downloads