How can I trim the sides of a string?

  • Thread starter Reply Via Newsgroup
  • Start date
R

Reply Via Newsgroup

Folks,

In PHP and some other scripting languages, one has trim() - It removes
newline, tabs and blank spaces that might prefix, or suffix a string.

Can someone tell me how I can do this in javascript?

Much appreciated,
randell d.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Michael Winter <[email protected]
d> posted at Sun, 2 May 2004 15:52:03 :
[snip]
String.prototype.trim = function()
{
return this.match(/(\b\S+|\S+)/g).join(" ");
}

The FAQ version seems to be more logical.

More importantly, it does what "randell d." asked for, whereas the
quoted code also converts multiple spaces within the string to singles.

That task can, AFAICS, be done by S.split(/\s+/).join(" "); and that
task might be worth including in the FAQ section, with optimum solution.
 
R

rh

Dr John Stockton said:
JRS: In article <[email protected]>, seen in
Michael Winter <[email protected]
d> posted at Sun, 2 May 2004 15:52:03 :
[snip]
String.prototype.trim = function()
{
return this.match(/(\b\S+|\S+)/g).join(" ");
}

The FAQ version seems to be more logical.

More importantly, it does what "randell d." asked for, whereas the
quoted code also converts multiple spaces within the string to singles.

That task can, AFAICS, be done by S.split(/\s+/).join(" "); and that
task might be worth including in the FAQ section, with optimum solution.

The FAQ version is clearly the correct way to trim strings. However,
I'm curious as to the reason the FAQ prototype is generated with "new
Function(str)" instead of the more common function-expression form
given above.

Strings introduce the requirement for double escaping the "\" (as per
new RegExp), and while such use may be instructive, it adds
chicken-track complexity where in a place where it doesn't appear to
be necessary.

Am I missing some subletly regarding browser compatibility, or
something to do with "this" association?

../rh
 
S

Shawn Milo

Reply Via Newsgroup said:
Folks,

In PHP and some other scripting languages, one has trim() - It removes
newline, tabs and blank spaces that might prefix, or suffix a string.

Can someone tell me how I can do this in javascript?

Much appreciated,
randell d.

There is a quick, easy way to do this with a regular expression.
It only takes one line of Javascript.

Code written, commented, and tested by me. No warranty. :eek:)

Shawn




<script type="text/javascript">


var testString = ' there are leading and trailing spaces (and tabs) ';

alert('\'' + testString + '\'');


//regex explanation:
//regex is in forward slashes: //
// syntax string = string.replace(/pattern/, 'replace with this');

^ = beginning of line
(\s+)? = one or more characters of whitespace, optional
(.*\S) = any characters, with the last one not being whitespace
(\s+)? = one or more characters of whitespace, optional
$ = end of line
$2 = what was in the 2nd set of parenthesis

testString = testString.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2');

alert('\'' + testString + '\'');

</script>
 
T

Thomas 'PointedEars' Lahn

rh said:
[...]
String.prototype.trim = function()
{
return this.match(/(\b\S+|\S+)/g).join(" ");
}

The FAQ version is clearly the correct way to trim strings. However,
I'm curious as to the reason the FAQ prototype is generated with "new
Function(str)" instead of the more common function-expression form
given above.

Strings introduce the requirement for double escaping the "\" (as per
new RegExp), and while such use may be instructive, it adds
chicken-track complexity where in a place where it doesn't appear to
be necessary.
Depends.

Am I missing some subletly regarding browser compatibility,

Yes, indeed you do. If Netscape's Core JavaScript Reference 1.5 and the
MSDN Library is to be trusted, the Function() constructor is available from
JavaScript 1.1 (NN3+) and JScript 2.0 (IE/IIS 3+) on, while the "function"
statement within another statement (including itself) or the "function"
operator (also defining anonymous functions) requires JavaScript 1.2 (NN4+)
or 1.5 (NN6+; in JScript AFAIS both are available in all versions and thus
all UAs), respectively. (Unfortunately, the Reference cannot be trusted
here since I had to learn that NN 4.7 which claims to support JavaScript
up to 1.3 only also supports the "function" operator.)

As for the ECMAScript standard, the "function" statement within a
statement is AFAIS not available before edition 3 as there is no
FunctionExpression to be produceable through the MemberExpression production.

While the UAs given respect to herewith may seem outdated, there may
be still UAs around which implement only those older versions of the
respective language(s). However, we also had one case of a buggy
implementation here that had b0rken Function() constructor support.
Google is your friend. [psf 6.1]

<http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/function.html#1193137>
<http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/stmt.html#1004825>
<http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/ops.html#1066344>
or something to do with "this" association?

No.

String.prototype.trim = new Function(
"return this.match(/(\\b\\S+|\\S+)/g).join(' ');");

is semantically equal to the above.


HTH

PointedEars
 
J

Jon Kelling

for all your javascript trimming needs...

function trim(inputString) {
if (typeof inputString != "string") return inputString;
return inputString
//clear leading spaces and empty lines
.replace(/^(\s|\n|\r)*((.|\n|\r)*?)(\s|\n|\r)*$/g,"$2")

//take consecutive spaces down to one
.replace(/(\s(?!(\n|\r))(?=\s))+/g,"")

//take consecutive lines breaks down to one
.replace(/(\n|\r)+/g,"\n\r")

//remove spacing at the beginning of a line
.replace(/(\n|\r)\s/g,"$1")

//remove spacing at the end of a line
.replace(/\s(\n|\r)/g,"$1");
}

-- Jon
 
B

bruce

function TrimSpacesFromBeginAndEnd (str)
{
pattern1=/[\s]+$/
pattern2=/^[\s]+/
y=str.replace(pattern2,"").replace(pattern1,"")
return y
}


This is assuming no unprintable characters...
 
R

rh

Thomas 'PointedEars' Lahn said:
rh said:
[...]
String.prototype.trim = function()
{
return this.match(/(\b\S+|\S+)/g).join(" ");
}

The FAQ version is clearly the correct way to trim strings. However,
I'm curious as to the reason the FAQ prototype is generated with "new
Function(str)" instead of the more common function-expression form
given above.

Strings introduce the requirement for double escaping the "\" (as per
new RegExp), and while such use may be instructive, it adds
chicken-track complexity where in a place where it doesn't appear to
be necessary.
Depends.

Am I missing some subletly regarding browser compatibility,

Yes, indeed you do. If Netscape's Core JavaScript Reference 1.5 and the
MSDN Library is to be trusted, the Function() constructor is available from
JavaScript 1.1 (NN3+) and JScript 2.0 (IE/IIS 3+) on, while the "function"
statement within another statement (including itself) or the "function"
operator (also defining anonymous functions) requires JavaScript 1.2 (NN4+)
or 1.5 (NN6+; in JScript AFAIS both are available in all versions and thus
all UAs), respectively. (Unfortunately, the Reference cannot be trusted
here since I had to learn that NN 4.7 which claims to support JavaScript
up to 1.3 only also supports the "function" operator.)

As for the ECMAScript standard, the "function" statement within a
statement is AFAIS not available before edition 3 as there is no
FunctionExpression to be produceable through the MemberExpression production.

While the UAs given respect to herewith may seem outdated, there may
be still UAs around which implement only those older versions of the
respective language(s). However, we also had one case of a buggy
implementation here that had b0rken Function() constructor support.
Google is your friend. [psf 6.1]

<http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/function.html#1193137>
<http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/stmt.html#1004825>
<http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/ops.html#1066344>
or something to do with "this" association?

No.

String.prototype.trim = new Function(
"return this.match(/(\\b\\S+|\\S+)/g).join(' ');");

is semantically equal to the above.


HTH

It does, thanks for taking the time to lay it out.

(I'm glad to see you got by my misspelling of subtlety above. Now if
we can just get you to use "broken" instead of "borken" and "b0rken"
-- or is this another psf-ism? :))

../rh
 

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,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top