472,119 Members | 1,390 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,119 software developers and data experts.

How can I trim the sides of a string?


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.
Jul 23 '05 #1
11 4592
Reply Via Newsgroup wrote:
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?


http://jibbering.com/faq/#FAQ4_16
JW

Jul 23 '05 #2
Reply Via Newsgroup wrote:

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.

http://www.vermontsoftware.com/Javascript/trim.html
Jul 23 '05 #3
Fox


pcx99 wrote:

Reply Via Newsgroup wrote:

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.


http://www.vermontsoftware.com/Javascript/trim.html

String.prototype.trim = function()
{
return this.match(/(\b\S+|\S+)/g).join(" ");
}
Jul 23 '05 #4
On Sun, 02 May 2004 07:03:20 -0500, Fox <fo*@fxmahoney.com> wrote:

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


The FAQ version seems to be more logical.

Mike

--
Michael Winter
M.******@blueyonder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 23 '05 #5
JRS: In article <op**************@news-text.blueyonder.co.uk>, seen in
news:comp.lang.javascript, Michael Winter <M.******@blueyonder.co.invali
d> posted at Sun, 2 May 2004 15:52:03 :
On Sun, 02 May 2004 07:03:20 -0500, Fox <fo*@fxmahoney.com> wrote:

[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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #6
rh
Dr John Stockton <sp**@merlyn.demon.co.uk> wrote in message news:<to**************@merlyn.demon.co.uk>...
JRS: In article <op**************@news-text.blueyonder.co.uk>, seen in
news:comp.lang.javascript, Michael Winter <M.******@blueyonder.co.invali
d> posted at Sun, 2 May 2004 15:52:03 :
On Sun, 02 May 2004 07:03:20 -0500, Fox <fo*@fxmahoney.com> wrote:

[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
Jul 23 '05 #7
Reply Via Newsgroup <re****************@please.com> wrote in message news:<FMjcc.30509$Pk3.9550@pd7tw1no>...
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. :o)

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>
Jul 23 '05 #8
rh wrote:
Fox <fo*@fxmahoney.com> wrote:
[...]
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>
<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsoriVersionInformation.asp>
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
Jul 23 '05 #9
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

pcx99 <x@x.com> wrote in message news:<eg****************@newssvr23.news.prodigy.co m>...
Reply Via Newsgroup wrote:

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.

http://www.vermontsoftware.com/Javascript/trim.html

Jul 23 '05 #10
function TrimSpacesFromBeginAndEnd (str)
{
pattern1=/[\s]+$/
pattern2=/^[\s]+/
y=str.replace(pattern2,"").replace(pattern1,"")
return y
}
This is assuming no unprintable characters...
Jul 23 '05 #11
rh
Thomas 'PointedEars' Lahn <Po*********@nurfuerspam.de> wrote in message news:<40**************@PointedEars.de>...
rh wrote:
Fox <fo*@fxmahoney.com> wrote:
> [...]
> 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>
<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsoriVersionInformation.asp>
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
PointedEars

Jul 23 '05 #12

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Rohit Yogi | last post: by
22 posts views Thread by Simon | last post: by
22 posts views Thread by Terry Olsen | last post: by
3 posts views Thread by Pascal | last post: by
31 posts views Thread by rkk | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.