RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: JavaScript
Expertise: Beginner
Feb 13, 2007

Trimming Spaces in JavaScript Using a Regular Expression

One simple way of trimming a string is to make use of a powerful regular expression—as opposed to iterating and removing the space characters one by one. To see how this works, save the code below as an .htm file, and then load the file into IE. Click in the text field and then tab out of it to see the code in action.

    <title>Trim String</title>

    <script language="javascript" type="text/javascript">
    function TrimString()
        var txtObj = document.getElementById("txtTrim");
        txtObj.value = txtObj.value.replace(/^\s+/,""); //Left trim        
        txtObj.value = txtObj.value.replace(/\s+$/,""); //Right trim
<input type="text" id="txtTrim" onblur="TrimString(this.value);" />
The JS code in the TrimString function replaces the space(s) character (identified as \s in the regular expression) with a blank or empty character.

Jayadev D
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date