FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?

F

FAQ server

-----------------------------------------------------------------------
FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?
-----------------------------------------------------------------------

Using Regular Expressions (JavaScript 1.2/JScript 4+) :

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

or for all versions (trims characters ASCII<32 not true
"whitespace"):

function LTrim(str) {
for (var k=0; k<str.length && str.charAt(k)<=" " ; k++) ;
return str.substring(k,str.length);
}
function RTrim(str) {
for (var j=str.length-1; j>=0 && str.charAt(j)<=" " ; j--) ;
return str.substring(0,j+1);
}
function Trim(str) {
return LTrim(RTrim(str));
}

http://msdn.microsoft.com/library/d...html/2380d458-3366-402b-996c-9363906a7353.asp

http://docs.sun.com/source/816-6408-10/regexp.htm


===
Postings such as this are automatically sent once a day. Their
goal is to answer repeated questions, and to offer the content to
the community for continuous evaluation/improvement. The complete
comp.lang.javascript FAQ is at http://jibbering.com/faq/index.html.
The FAQ workers are a group of volunteers.
 
N

Noah Sussman

The first two regex functions are both named "lTrim."

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

-Lost

Noah said:
The first two regex functions are both named "lTrim."

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

Yep. The second "lTrim" should be "rTrim."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top