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?
43 comments. Current rating: (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.
 | |  | |
<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 3 of 3, other pages: 1 2 [3] | |
|
|
|
THANKS SO MUCH!
|
|
|
|
|
I've encountered a problem where MSIE uses \r\n at line breaks while Firefox only inserts the \n
Since I'm splitting the lines a \n how can trim() be updated to remove the \r at the end of the line?
I haven't tested trim() with \t but I'd like to remove them too.
|
|
|
|
|
String.prototype.trim = function()
{
return this.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\r*$/,'');
}
This updated version will remove any \r carriage return symbol at the end of a data line inserted by MSIE. I use it after a data = data.split('\n'); call to turn the data into individual lines for parsing.
|
|
|
|
|
Excellent
|
|
|
|
|
d
|
|
|
|
|
it's very good
|
|
|
|
|
Thanks dude. Saved a lot of my R&D
|
|
|
|
|
Great Code love it!!!!
|
|
|
|
|
it is not working if the string contains /
|
|
|
|
|
thank for the code.
|
|
|
|
|
realyy helpfull. thanks
|
|
|
|
|
|
|
|
|
|
Thanks!!!
|
| You are on page 3 of 3, other pages: 1 2 [3] |
|