Skip Navigation

About This Website

CodeStore is all about web development. Mostly with the Lotus Domino server.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »

About This Page

Written by Jake Howlett on Mon 13 Mar 2006

Permalink: Tips Week 2.1 - JavaScript Trim() Function

Skip to the comments or add your own.

You can subscribe to an individual RSS feed of comments on this entry.

Recent Comments

Elsewhere

Here are the external links posted on the same day.

More links are available in the archive »

Tips Week 2.1 - JavaScript Trim() Function

I'm going to be too busy this week to blog anything insightful, so I'll do another tips week. Starting today with a little extension to the JavaScript String object.

Add this function to a JS library somewhere:

String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};

Then you can call is from wherever you like, as so:

alert(" test" + " this ".trim() )

The result of which is a prompt showing " test this". Or use like this:

<input type="test" onchange="this.value=this.value.trim()" >

It's a useful function. Don't leave home without it.

More String extensions here. More tips each day this week.

Comments

  1. Ummm. Is that a typo? Surely the alert above should return " testthis".

    You could shorten this to something like;

    return this.replace(/^\s*(\b.*\b|)\s*$/, '');

    which will remove leading/trailing whitespaces. But does anybody have anything which will act like @Trim and cut out whitespaces in the middle of strings?

    • avatar
    • Jake
    • Posted on Mon 13 Mar 2006 07:05 AM

    Woops. Yes. It is and it will.

  2. Ah. Here we go. A Regexp which will remove repeated whitespaces and replace with a single space.

    return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");

    Not perfect (turns tabs into spaces) but close enough for me.

  3. Trim is always useful. That's why I have these:

    String.prototype.trim = function() {

    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");

    }

    String.prototype.fulltrim = function() {

    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ");

    }

    Not sure whether they bring anything else to the party. But I have been using them for a long while and hand no complaints, yet.

    • avatar
    • Vince
    • Posted on Mon 13 Mar 2006 08:03 AM

    A couple other handy ones include:

    String.prototype.right = function(count) {

    return this.substr(this.length - count);

    }

    String.prototype.left = function(count) {

    return this.substr(0, count);

    }

    • avatar
    • Ron Yuen
    • Posted on Tue 14 Mar 2006 04:02 AM

    Duplicating Lotusscript/@Formula functions in Javascript is frequently useful, I have found the @Unique(list) capability especiually so.

    here is a JS version :

    Array.prototype.indexOf = function(str,ignoreCase) {

    // return the index of the first instance of str in the array

    // else -1 if not a member

    // if a string array can take a flag to request case match

    // if (ignoreCase) then 'StringA' is considered the same as 'sTrinGa'

    var tmp ;

    if (typeof(str)=="string" && ignoreCase) {

    str = str.toLowerCase() ;

    }

    for (var i=0; i<this.length; i++) {

    if (typeof(str)=="string" && ignoreCase) {

    tmp=this[i].toLowerCase() ;

    } else {

    tmp=this[i] ;

    }

    if (tmp==str) return i ;

    }

    return -1 ;

    }

    Array.prototype.isMember = function(str,ignoreCase) {

    return this.indexOf(str,ignoreCase) > -1 ;

    }

    Array.prototype.unique = function(ignoreCase) {

    // creates a unique array

    // empty arrays are always unique !

    if (this.length==0) return this ;

    // default to respect case

    // if (ignoreCase) then 'StringA' is considered the same as 'sTrinGa'

    if (arguments.length==0) ignoreCase = false ;

    var newList = new Array(this[0]) ;

    var found,tmp1,tmp2 ;

    for (var i=0; i<this.length; i++) {

    if (!newList.isMember(this[i],ignoreCase)) newList.push(this[i]) ;

    }

    return newList ;

    }

    To be really bulletproof you may want to check that the browser supports array.push() and if not then implement one !

    Regards

    Ron Yuen

    • avatar
    • Ady
    • Posted on Wed 17 May 2006 01:56 PM

    Hi Jake et al,

    Anyone know how 'fully' @Trim an html textarea?

    e.g. create an editable text field with, say 5 rows and 20 cols, and allow multiple values. Then populate the text area with just spaces and carriage returns.

    If you put @Trim(@ThisValue) in the Input Translation and submit the form then all the 'whitespace' is removed, but there doesn't seem to be a way to do this in javascript prior to submitting the form...

    Any ideas anyone?!

    • avatar
    • Robert
    • Posted on Mon 14 Aug 2006 08:34 PM

    //*** removes whitespace fom begining and end of a string and returns it to whereever.

    function trim(string){

    if(string.indexOf(" ") == 0){

    while(string.indexOf(" ") < 1){

    string = string.substring(1,string.length) ;

    }

    }

    if(string.substring(string.length-1,string.length) == " "){

    while(string.substring(string.length-1,string.length) == " "){

    string = string.substring(0,string.length-1) ;

    }

    }

    return string;

    }

    function yourFunction(str){

    ....

    str = trim(str);

    ....

    }

    • avatar
    • Jorge
    • Posted on Mon 25 Sep 2006 07:32 AM

    Thank you very much.

    This little func was just what i was looking for.

    Keep it up !

    • avatar
    • Pete
    • Posted on Fri 5 Jan 2007 06:24 AM

    Robert's code is flawed. If the string has leading spaces but no trailing spaces then it will get caught in an infinite loop.

    Here's a version that will allow for leading spaces only, trailing spaces only, both leading and trailing spaces and no leading or trailing spaces.

    function trim(string){

    ' remove leading spaces

    while(string.substr(0,1)==" ")

    string = string.substring(1,string.length) ;

    ' remove trailing spaces

    while(string.substr(string.length-1,1)==" ")

    string = string.substring(0,string.length-2) ;

    return string;

    }

    • avatar
    • Sowmya
    • Posted on Thu 8 Mar 2007 03:31 AM

    I need the following output:

    I have a variable in which the value it has is:

    " 1 : 3300"

    I need to trim it to 3300 and store it as an integer.

    How is it possible?

    Please do reply.

    Thank you,

    Regards,

    Sowmya,

    Bangalore, India

  4. There are many required functions which are not available in Native JavaScript.Get trim and more functions like trim() for JavaScript:

    {Link}

    • avatar
    • Russell
    • Posted on Thu 14 Feb 2008 11:34 PM

    Sowmya ,

    use trim function...

    smthing like

    strObj.trim(":")[1]

    • avatar
    • Ryan
    • Posted on Wed 21 May 2008 09:37 AM

    Have a look at this article for more ways of implementing javascript trim: {Link}

    • avatar
    • Jason
    • Posted on Thu 5 Feb 2009 05:43 PM

    I looked through these functions trying a few of the examples finding them to behave differently then what I was looking for as a quick fix. When I think of a trim function I am thinking the results return a string minus the leading and trailing spaces.

    For you who wanted to remove all spaces, there is no reason to loop through a string to remove them.. just use str.replace(' ',''); end of story.

    I ended up writing this little script prototyping String as well, this will remove all leading and trailing spaces leaving the inner string untouched. Hope it helps..

    String.prototype.trim = function() {

    var str = this;

    var firstChar = str.substring(0,1);

    while(firstChar == ' '){

    str = str.substring(1,(str.length))

    firstChar = str.substring(0,1);

    }

    var lastChar = str.substring(str.length - 1, str.length);

    while(lastChar == ' '){

    str = str.substring(0,str.length - 1);

    lastChar = str.substring(str.length - 1, str.length);

    }

    return str;

    }

    • avatar
    • DUzun
    • Posted on Sat 7 Feb 2009 01:28 PM

    I don't like using regexp, but sometimes you need to remove the tabs too, not only the spaces.

    The above example is good, but it is very slow!

    Using str = str.substr(0, str.length-1) in a loop is not a good practice, just because it copies the entire string a lot of times.

    I prefer checking where is the begining and the end of my trimed string, then to cut it at once:

    String.prototype.trim = function()

    {

    var b = 0 ;

    var e = this.length - 1 ;

    while( this.substr(b, 1).match(/\s/) ) b++ ;

    while( this.substr(e, 1).match(/\s/) ) e-- ;

    return this.substr(b, e-b+1);

    }

    Hope this will help somebody!

    • avatar
    • Biswa
    • Posted on Sat 1 Aug 2009 02:56 AM

    Previously we are writing to trim a string object ,with your script it's very easy to trim any thing we want very smoothly.

    Thnks

    • avatar
    • Scott Bishop
    • Posted on Fri 30 Apr 2010 03:26 PM

    I prefer the original author's version, however it can be written as one line rather than 2:

    String.prototype.trim = function() {

    return this.replace(/^\s+ | \s+$/g,'')

    }

Add your own response here:

Although your email address isn't required it is protected from spambots if you choose to provide it and not to hide it. My right to remove commercial, irrelevant or posts I just don't like is reserved.

Name *:
E-mail:
Website:
 

Comment *:

HTML is not allowed!