It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming JavaScript Forum Script-archive

JavaScript String Trim

JavaScript String Trim

Postby HotNoob on Tue Sep 28, 2010 5:02 pm

This is just a little bit of code that adds a trim function(a function that removes trailing white spaces)

simple add this to your page
Code: Select all
<script>
String.prototype.trim = function ()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
</script>

Then to use it
Code: Select all
var str = 'trim this ';
str.trim();
alert("'"+str+"'"); //will alert 'trim this'


Enjoy.
HotNoob
100+ Club
 
Posts: 169
Joined: Sun May 02, 2010 1:38 am

Re: JavaScript String Trim

Postby bardonw on Mon Apr 11, 2011 2:56 pm

Good post! I think it is important to note that you don't want to overwrite the native function if it exists for the browser that is being used. Also, you want to make sure you remove instances of character 160 (in hex it is A0). Therefore, the following code is probably a better approach at making the trim function available for all browsers:
Code: Select all
String.prototype.trim = String.prototype.trim || function () {
    return this.replace(/^[\u00A0\s]+/, "").replace(/[\s\u00A0]+$/, "");
}


In addition, if you are using a JavaScript that provides the curry function, you may want to check out this post which shows you how to add trim, trimLeft, and trimRight in four short lines.
bardonw
 
Posts: 7
Joined: Tue Feb 15, 2011 4:16 pm


Who is online

Users browsing this forum: No registered users and 0 guests