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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
Comment and Contribute






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



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