Re: FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?
- From: Dr J R Stockton <jrs@xxxxxxxxxxxxxxxxxx>
- Date: Fri, 2 Nov 2007 13:22:17 +0000
In comp.lang.javascript message <1193957400.023804.169070@xxxxxxxxxxxxxx
oglegroups.com>, Thu, 1 Nov 2007 22:50:00, Peter Michaux
<petermichaux@xxxxxxxxx> posted:
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);
}
It is often considered good practice for the terminal condition of a FOR
loop to be constant during that loop, to reduce confusion. Therefore
(undertested) :-
function lTrim(str) { var k = 0
while( k<str.length && str.charAt(k)<=" ") k++
return str.substring(k, str.length);
}
function rTrim(str) { var k = str.length-1
while (k>=0 && str.charAt(k)<=" ") k--
return str.substring(0, k+1);
}
Functions, except maybe when one-liners, should be separated by vertical
whitespace, for legibility. And k is better than j.
The character l should not be used where it might be, even momentarily,
thought to be a 1. Therefore, the names might be changed to trimL and
for symmetry trimR, matching trim in case. To facilitate searching for
the identifier, I suggest trim be renamed to trimX (X for eXtremes).
And "ASCII<32" is wrong, since the characters are UniCode.
--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
For news:borland.*, use their server newsgroups.borland.com ; but first read
Guidelines <URL:http://www.borland.com/newsgroups/guide.html> ff. with care.
.
- References:
- Re: FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?
- From: Peter Michaux
- Re: FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?
- Prev by Date: Re: comp.lang.javascript Cookbook Proposal
- Next by Date: Re: comp.lang.javascript Cookbook Proposal
- Previous by thread: Re: FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?
- Next by thread: Re: FAQ Topic - How do I trim whitespace - LTRIM/RTRIM/TRIM?
- Index(es):
Relevant Pages
|