DelphiFAQ Home Search:

How can I trim a string in JavaScript?


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


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


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
alert("!" + s + "!");

// end hiding contents -->

Content-type: text/html


You are on page 1 of 4, other pages: [1] 2 3 4
2007-05-19, 02:15:14
[hidden] from Pakistan  
function trim(s)
    var l=0; var r=s.length -1;
    while(l < s.length && s[l] == ' ')
    {     l++; }
    while(r > l && s[r] == ' ')
    {     r-=1;     }
    return s.substring(l, r+1);
2007-07-16, 01:04:39
anonymous from India  
for the code mentioned by [hidden] from Pakistan, i had seen that s[l] is actually undefined and it does not give any valid character if we use s[l] .

so better use the following code:

function trimAll(sString)
while (sString.substring(0,1) == ' ')
sString = sString.substring(1, sString.length);
while (sString.substring(sString.length-1, sString.length) == ' ')
sString = sString.substring(0,sString.length-1);
return sString;

-Afzal Aziz
2007-10-03, 05:58:22   (updated: 2007-10-03, 05:59:56)
anonymous from India  
Thanks for giving this trim function
2007-11-06, 06:52:58
anonymous from Dominican Republic  
2007-12-05, 00:39:38
anonymous from India  
2008-05-20, 10:44:59   (updated: 2008-05-20, 10:46:28)
anonymous from United States  
Great function !!!! Just copied, pasted and used it. THANKS !!!
2008-06-09, 04:27:14
anonymous from Indonesia  
Very helpful, thaks..
2008-06-17, 10:56:02
anonymous from United States  
Gr8 compact function thanks
2008-06-19, 09:45:29   (updated: 2008-06-19, 09:46:23)
Andrew from Columbia, United States  
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='';;
                        if(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  
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  
2008-09-22, 03:47:41
anonymous from India  
I am searching information on string trimmers and I have visited one site 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
You are on page 1 of 4, other pages: [1] 2 3 4



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:

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.

photo Add a picture: