• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Trimming strings with Javascript

Trimming strings with Javascript

Javascript does not have built-in functions to trim strings so they need to be defined either by using a Javascript framework/library such as jQuery which includes a trim function or to define trim functions yourself. This post shows how to create trim() ltrim() and rtrim() functions.

Here’s the functions:

function trim(text) {
    return text.replace(/^s+|s+$/g, "");
}
function ltrim(text) {
    return text.replace(/^s+/g, "");
}
function rtrim(text) {
    return text.replace(/s+$/g, "");
}

And here’s them working with the string "   aaa   ". The input has a [ and ] outside the aaa text so you can see how it’s been trimmed. Note this is unlikely to work if you are viewing this in an RSS feeder so click through to view this page in a web browser.

The code for the above example looks like this:

var aaa = "   aaa   ";
document.write('No trim:<br /><input type="text" size="10" value="[' + aaa + ']" /><br />');
document.write('trim:<br /><input type="text" size="10" value="[' + trim(aaa) + ']" /><br />');
document.write('ltrim:<br /><input type="text" size="10" value="[' + ltrim(aaa) + ']" /><br />');
document.write('rtrim:<br /><input type="text" size="10" value="[' + rtrim(aaa) + ']" /><br />');

The jQuery Way

If you use jQuery you can use the jQuery $.trim() function instead. However, there are not left and right trim functions in jQuery, so if you need these you will still need to define them yourself.

Doing the above with jQuery:

var aaa = "   aaa   ";
document.write('No trim:<br /><input type="text" size="10" value="[' + aaa + ']" /><br />');
document.write('trim:<br /><input type="text" size="10" value="[' + $.trim(aaa) + ']" /><br />');

Check Out These Related posts:

  1. Show and hide an element with jQuery
  2. Toggling a password field between plain text and password
  3. Setting default values for missing parameters in a Javascript function
  4. Multiple variable assignment with Javascript

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap