DelphiFAQ Home Search:

How can I trim a string in JavaScript?

 

comments43 comments. Current rating: 5 stars (15 votes). Leave comments and/ or rate it.

Question:

I need to trim a string from white space at the front and end. How can I do that elegantly?

Answer:

Add the following string prototype function to your code. You will call it like predefined String member functions (such
as indexOf(), charAt() and Substring().

The code below shows the function declaration and how to use it.

This implementation of a trim() function uses two regular expressions to first replace the white space at the begiinning,
then the white space at the end of the string. White space in regular expressions is described as \s.
The beginning of the string is matched by ^ (see the first regex) and the end is matched by $ - in the second regex.

// implementing a trim function for strings in javascript

<script language="JavaScript" type="text/javascript">
<!--
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

var s = new String(" Hello ");
// use it like this
s=s.trim();
alert("!" + s + "!");

// end hiding contents -->
</script>


Comments:

You are on page 2 of 3, other pages: 1 [2] 3
2008-06-19, 09:45:29   (updated: 2008-06-19, 09:46:23)
Andrew from Columbia, United States  
rating
Very useful. Who would have thunk that Javascript doesn't have an inbuilt trim function? I always assumed it did...
2008-07-04, 04:24:09
anonymous from Bulgaria  
            function trim(str)
            {
                    var newStr='';;
                    for(i=0;i<str.length;i++)
                    {
                        if(str[i]!=' ')
                        {
                            newStr+=str[i];
                        }
                    }
                    return newStr;
            }
2008-07-08, 12:21:12   (updated: 2008-07-08, 12:55:07)
joe from United States  
Its slightly faster to combine the regular expressions into a single one. In fact its even faster to make this a standalone function into of being a prototype on String but if you want to keep it that way, here it is:

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

(If anyone wants benchmarks let me know)

Please remove the picture... I thought it would be a gravatar or something...
2008-08-15, 16:35:07   (updated: 2008-08-15, 16:36:05)
anonymous from Morrisville, United States  
rating
Regular expression is fine.
Otherwise, the fastest I have found is this one:

function trimString(s)
{
if ((s == null)||(s.length == 0))
return s;

for(var start = 0; s.charCodeAt(start) == 32; start++)
if (start == s.length-1)
return '';

for(var end = s.length-1; s.charCodeAt(end) == 32; end--);

return s.substring(start, end+1);
}
2008-09-17, 09:06:57
anonymous from Morrisville, United States  
I did some benchmark with ie 7.0 and ff 3.0. (ff is much faster)

reg exp is faster when we remove at least:
In IE: 6 Spaces
In FF: 20 Spaces

Otherwise, trimString(s) by hand is faster.
2008-09-18, 08:22:35
anonymous from India  
Gr8
2008-09-22, 03:47:41
anonymous from India  
hi
I am searching information on string trimmers and I have visited one site http://www.sharperblade.com. If anybody knowing about string trimmers and you spot any issues that need to be fixed and or improved please let me know as soon as possible.

thank you
2008-11-08, 09:19:32
jobi from India  
Thank you very much saved some of my time...
2008-12-04, 15:03:29
anonymous from Cary, United States  
rating
Notice that the regular expression posted by joe:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}

is the same than the one used by Microsoft in their ajax API:
function String$trim()
{
/// <summary locid='M:J#String.trim' />
/// <returns type='String'></returns>
if (arguments.length !== 0) throw Error.parameterCount();
return this.replace(/^\s+|\s+$/g, '');
}
2008-12-18, 05:38:16
anonymous from India  
Hello ,
I have a string like 'Error:Error: Hello World calling service createHelloWorld in createUpdateHelloWorld' I want only Hello world and have to remove Error:Error: calling service createHelloWorld in creatUpdateHelloWorld .......how can I do this.

Any help is much appreciated.
2008-12-19, 11:24:37
anonymous from India  
Good one thanks
2009-01-06, 23:33:29
anonymous from United States  
Hi,

I want to trim <p>text </p> it to as text in javascript.

Could anyone help out me in uregently.

Send your reply to rajuavs82@yahoo.com or rajuavs82@gmail.com

Thanks in Advance.

Regards,
Raju.
2009-01-19, 00:19:54
anonymous from India  
7550 7550 7550 7550 7550 7550 7550 7550 7550
2009-02-18, 00:56:17
anonymous from India  
aaaaaaaaaaaaaaaaa


Keywords:
You are on page 2 of 3, other pages: 1 [2] 3

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:
photo Add a picture:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity. The owner of this web site reserves the right to delete such material.