Version 19 of string trim

Updated 2015-05-17 17:10:48 by MiHa

Description

Returns a value equal to string except that any leading or trailing characters that occur in chars are removed.
If chars is not specified then white space is removed (spaces, tabs, newlines, and carriage returns).

string trim removes characters from the beginning and end of a string.

Synopsis

string trim string ?chars?

Demo 1

# http://ideone.com/IX2f6Y
 set s1 " Hello "
 set s2 [string trim $s1]
 puts "<$s1> <$s2>"
#
 set s1 "*** Hello_###"
 set s2 [ string trim $s1 "*#_" ]
 puts "<$s1> <$s2>"
#. 

Result:

< Hello > <Hello>
<*** Hello_###> < Hello>

Demo 2

# http://codepad.org/b4bHNWjo
 set s1 " * Hello ** "
 set s2 [string trim $s1]
 set s3 [string trim $s1 " *"]
 puts "<$s1>\n<$s2>\n<$s3>"
#. 

Result:

< * Hello ** >
<* Hello **>
<Hello>

See Also

What Constitutes Whitespace

See TIP #318: Extend Default Whitespace in 'string trim' Beyond ASCII .

escargo 2008-06-02: This also related to behavior discussed in comp.lang.tcl with the subject, "string trim not trimming special space characters" (starting on 2008-03-04).

The characters removed by string trim string (with no chars argument) are not all the ones for which string is space char returns 1.

I think the TIP should also include Unicode nonbreaking spaces.

LV: You could either update the TIP page with your concerns, or post a comment over on the TCT mailing list.

Remarks

MiHa 2015-05-17: As I already ranted, missing examples are a common shortcoming in the docs.
As an example, how I would like examples done (here in the wiki, as well as in the help-system
that comes with the tcl/tk-installation, I added a demo-section,
with links to two different online-compilers, where the examples can be seen "live".