Trimming strings with Javascript
Posted June 16th, 2009 in 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 />');
Related posts:
- Upper and lower case strings with Javascript (Tuesday, September 15th 2009)
- Substrings in Javascript with substring() (Friday, July 24th 2009)
- Substrings in Javascript with substr() (Tuesday, July 21st 2009)
- Multi line strings with Javascript (Tuesday, May 26th 2009)
- Replacing text with Javascript (Tuesday, February 10th 2009)
- Find the index of a string within a string with Javascript (Friday, November 28th 2008)

Comments
blog comments powered by Disqus