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 />');