What's a clean and efficient Javascript implementation to strip leading and trailing spaces from a string?
for example " dog", "dog ", " dog ", " dog " all get turned into "dog"
What's a clean and efficient Javascript implementation to strip leading and trailing spaces from a string?
for example " dog", "dog ", " dog ", " dog " all get turned into "dog"
Use this:
if(typeof(String.prototype.trim) === "undefined")
{
String.prototype.trim = function()
{
return String(this).replace(/^\s+|\s+$/g, '');
};
}
The trim function will now be available as a first-class function on your strings. For example:
" dog".trim() === "dog" //true
EDIT: Took J-P's suggestion to combine the regex patterns into one. Also added the global modifier per Christoph's suggestion.
Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.
Here's the function I use.
function trim(s){
return ( s || '' ).replace( /^\s+|\s+$/g, '' );
}
Steven Levithan once wrote about how to implement a Faster JavaScript Trim. It’s definitely worth a look.
If, rather than writing new code to trim a string, you're looking at existing code that calls "strip()" and wondering why it isn't working, you might want to check whether it attempts to include something like the prototypejs framework, and make sure it's actually getting loaded.
That framework adds a strip function to all String objects, but if e.g. you upgraded it and your web pages are still referring to the old .js file it'll of course not work.