JavaScript Document (8) Events (8) ExtJS (9) Strings (3)
Exchange Links About this site Links to us 
|
How can I trim a string in JavaScript?
45 comments. Current rating: (16 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.
 | |  | |
<script language="JavaScript" type="text/javascript">
<!--
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
var s = new String(" Hello ");
s=s.trim();
alert("!" + s + "!");
</script>
| |  | |  |
Comments:
| You are on page 1 of 3, other pages: [1] 2 3 | |
[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);
}
|
|
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
Raviiiii......
|
|
anonymous from Dominican Republic
|
|
|
|
GOOOODDD
|
|
anonymous from India
|
 |
|
|
Cool
|
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 !!!
|
|
anonymous from Indonesia
|
 |
|
|
Very helpful, thaks..
|
|
anonymous from United States
|
 |
|
|
Gr8 compact function thanks
|
| You are on page 1 of 3, other pages: [1] 2 3 |
|