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=new Function("return this.replace(/^\\s+/,'')")
String.prototype.RTrim=new Function("return this.replace(/\\s+$/,'')")
String.prototype.Trim=
new 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.
 
A

Andrew Poulos

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

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

String.prototype.LTrim=new Function("return this.replace(/^\\s+/,'')")
String.prototype.RTrim=new Function("return this.replace(/\\s+$/,'')")
String.prototype.Trim=
new Function("return this.replace(/^\\s+|\\s+$/g,'')")

What would also be useful is another prototype that reduces multiple
contiguous spaces to a single space.

I don't have it at hand but someone here kindly wrote one for me.

Andrew Poulos
 
E

Evertjan.

Andrew Poulos wrote on 22 feb 2007 in comp.lang.javascript:
What would also be useful is another prototype that reduces multiple
contiguous spaces to a single space.

String.prototype.whiteSpaces2singleSpace =
new Function("return this.replace(/\\s\\s+/g,' ')")
 
U

Une Bévue

Evertjan. said:
String.prototype.whiteSpaces2singleSpace =
new Function("return this.replace(/\\s\\s+/g,' ')")


writing :

....(/\s\s+/g,' ')...

isn't sufficient no need to escape \ ???

ami i wrong ?
 
E

Evertjan.

Une Bévue wrote on 22 feb 2007 in comp.lang.javascript:
writing :

...(/\s\s+/g,' ')...

isn't sufficient no need to escape \ ???

ami i wrong ?

Did you try?
 
E

Evertjan.

Une Bévue wrote on 22 feb 2007 in comp.lang.javascript:

Nonsense, you did not try,
but did quite someting else!

You did this:

var s = p.replace(/\s\s+/g, ' ');

While my line was:

String.prototype.whiteSpaces2singleSpace =
new Function("return this.replace(/\\s\\s+/g,' ')")

Please try that with /\\s\\s+/g replaced by /\s\s+/g

.... and you will see what goes wrong.

Do you know what goes wrong?
and i'm TRUE ;-)

Are you Boolean?
 
U

Une Bévue

Evertjan. said:
Please try that with /\\s\\s+/g replaced by /\s\s+/g

i have added the /\\s\\s+/g for t right now
Do you know what goes wrong?

Not at all because i thought the purpose of the Regexp was to replace

multiple white spaces by single one, as the name :

String.prototype.whiteSpace2singleSpace implies ???
 
T

Tim Streater

i have added the /\\s\\s+/g for t right now


Not at all because i thought the purpose of the Regexp was to replace

multiple white spaces by single one, as the name :

String.prototype.whiteSpace2singleSpace implies ???

Safari doesn't like your toolkit.js as there is an extra , on line 348
or so. FF didn't seem to mind.

-- tim
 
E

Evertjan.

Une Bévue wrote on 22 feb 2007 in comp.lang.javascript:
i have added the /\\s\\s+/g for t right now


Not at all because i thought the purpose of the Regexp was to replace

multiple white spaces by single one, as the name :

String.prototype.whiteSpace2singleSpace implies ???

You are on the wrong track.

new Function() here has a string as parameter,
and in javascript strings backslashes are used as escape characters.
If you need the backslashes, you will have to escape them themselves.
This is ONLY required in a string,
not in a regex declaration without a string.

Try this:

====================================
<script type='text/javascript'>

alert("return this.replace(/\s\s+/g,' ')");

alert("return this.replace(/\\s\\s+/g,' ')");

</script>
=====================================
 
U

Une Bévue

Evertjan. said:
new Function() here has a string as parameter,
and in javascript strings backslashes are used as escape characters.
If you need the backslashes, you will have to escape them themselves.
This is ONLY required in a string,
not in a regex declaration without a string.

OK, i see what u mean )))

BUT why did them use :

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

i don'undetstand why u (them) are passing a constant as an argument ???
 
U

Une Bévue

Tim Streater said:
Safari doesn't like your toolkit.js as there is an extra , on line 348
or so. FF didn't seem to mind.

Fine, thanks, repaired ))

i let the last "," in order not to forget it when cut'n paste )))
 
E

Evertjan.

Une Bévue wrote on 22 feb 2007 in comp.lang.javascript:
OK, i see what u mean )))

BUT why did them use :

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

i don'undetstand why u (them) are passing a constant as an argument ???

No, it is called a string litteral, javascript has no constants.

I don't know why, both work.
 
U

Une Bévue

Evertjan. said:
No, it is called a string litteral, javascript has no constants.

Ok. However a string litteral which doesn't vary ))
I don't know why, both work.

i never used that kind of syntax for a function :

new Function("what u want to be done");

i did a little experiment like that :

String.prototype.hello= new Function("alert('Hello World!')");
"".hello();

and it works fine !
 
I

Isaac Schlueter

What would also be useful is another prototype that reduces multiple
contiguous spaces to a single space.

So, am I the only one who finds this syntax horrible to look at?
Isn't this easier?

// converted to camelCase to match every other member function in
Javascript.
String.prototype.lTrim=function () { return this.replace(/^\s
+/,''); };
String.prototype.rTrim=function () { return this.replace(/\s+
$/,''); };
String.prototype.trim= function () { return this.replace(/^\s+|\s+$/
g,''); };

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

What's the advantage of using
new Function( 'blah blah blah' )
instead of
function () { blah blah blah }
besides increasing the risk of errors due to unescaped characters?

In my opinion, as a general rule, eval is evil. The same goes for all
the other cases where a string literal is executed as code.
They open up the door for simple errors that are tricky to catch. The
browsers that required these approaches are all but extinct, and new
systems tend to implement the native function object approach. If
there is any other way to get the job done, it's probably best to
avoid executing a string as code.
 
E

Evertjan.

Isaac Schlueter wrote on 23 feb 2007 in comp.lang.javascript:
So, am I the only one who finds this syntax horrible to look at?
Isn't this easier?

// converted to camelCase to match every other member function in
Javascript.
String.prototype.lTrim=function () { return this.replace(/^\s
+/,''); };
String.prototype.rTrim=function () { return this.replace(/\s+
$/,''); };
String.prototype.trim= function () { return this.replace(/^\s+|\s+$/
g,''); };

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

I think you are right on both accounts,
the lowercase naming and the eventual evil eval-ness.
What's the advantage of using
new Function( 'blah blah blah' )
instead of
function () { blah blah blah }
besides increasing the risk of errors due to unescaped characters?

The only advantage could be dynamic defining by manipulation of the
defining string, but even here, you can easily do without:

function makeTrimProto(name,rgx){
String.prototype[name] = function ()
{ return this.replace(rgx,' '); };
};

makeTrimProto('lTrim', /^\s+/);
makeTrimProto('rTrim', /\s+$/);
makeTrimProto('trim', /^\s+|\s+$/g);
makeTrimProto('singleSpace', /\s\s+/g);
In my opinion, as a general rule, eval is evil.
[..]
 
R

Richard Cornford

Isaac Schlueter wrote on 23 feb 2007 in comp.lang.javascript:

The only advantage could be dynamic defining by manipulation of the
defining string, but even here, you can easily do without:
<snip>

That is not the only reason (and it easily could be argued that it is
not a good idea to be dynamically manipulating script code on the
client, it certainly introduces an additional layer of issues that
probably should be avoided). The other good reason for using the
Function constructor is to create function objects that have a minimum
scope chain from a context that would impose a more involved scope
chain on any inner functions created within it.

<FAQENTRY>Randy, these trim function examples probably are candidates
for moving away from function constructor use to the use of function
expressions. Because they are - String.prototype - extensions we can
be pretty sure they will be evaluated in the global execution context
and so the scope chains of the functions will not differ depending on
the creation method, and by now we must be past the point where
continuing to accommodate browsers that did not understand function
expressions (pre-IE4, Netscape 4) is pointless.</FAQENTRY>

Richard.
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
glegroups.com>, Fri, 23 Feb 2007 02:51:36, Richard Cornford
by now we must be past the point where
continuing to accommodate browsers that did not understand

<FAQENTRY>

IMHO, the FAQ should contain a statement along the general lines of

"In general, the code in this FAQ is for MSIE 4, Netscape 5, Opera 6,
Firefox 7, and equivalent or later browsers. Much of it will work on
older systems. Where code will not work on those above, or is present
specifically to support earlier browsers, that will be noted in or by
the code."

If a draft subsection for that is posted here, with a list of the places
where such markings are known to be needed, then discussion should
quickly enough yield a generally-acceptable list of browsers and places
to be marked.

Consider also, though, javascript in non-browsers.
 
R

Randy Webb

Richard Cornford said the following on 2/23/2007 5:51 AM:


<FAQENTRY>Randy, these trim function examples probably are candidates
for moving away from function constructor use to the use of function
expressions.

The code that I now have locally is this:

String.prototype.LTrim=function(){return this.replace(/^\s+/,'')}
String.prototype.RTrim=function(){return this.replace(/\s+$/,'')}
String.prototype.Trim=function(){return this.replace(/^\s+|\s+$/g,'')}

If there are not problems/errors with it I will get it uploaded.

The Number.toFixed entry and the DynWrite entries also use new Function.

I will work on those two tonight and tomorrow (to do some testing) and
post the proposed changes to the code for review.
 
D

Dr J R Stockton

In comp.lang.javascript message said:
The code that I now have locally is this:

String.prototype.LTrim=function(){return this.replace(/^\s+/,'')}
String.prototype.RTrim=function(){return this.replace(/\s+$/,'')}
String.prototype.Trim=function(){return this.replace(/^\s+|\s+$/g,'')}

Others have already asked you to make better use of whitespace in FAQ
code.


String.prototype.LTrim =
function() { return this.replace(/^\s+/, "") }
String.prototype.RTrim =
function() { return this.replace(/\s+$/, "") }
String.prototype.Trim =
function() { return this.replace(/^\s+|\s+$/g, "") }
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top