Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
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.

<html>
<head>
    <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
    }
    </script>
</head>
<body>
<input type="text" id="txtTrim" onblur="TrimString(this.value);" />
</body>
</html>
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
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap