Extra functionality for trim()

While trim() is useful, even more useful would be the ability to remove arbitrary characters from either or both ends of a string. I’d suggest something like:

newstr = oldstr.Trim (trstr)

to remove any of the characters in trstr from both ends of oldstr. Before submitting a Feature Request, I’m curious whether anyone else would find it useful.


Hi @TimStreater, maybe you’ll find more useful using regular expressions for that?

Or create your own function and put it in a module:

Public Function Trim(Extends s As String, chars As String) As String
  // Code
End Function

I definitely would want

newstr = oldstr.Trim (trstr)

To trim something else than spaces from either end. (like you can do in many languages)

Could be upgrade of the old one adding default parameter where the default is " "

1 Like

:slight_smile: I thought someone might suggest that.

It usually takes me half an hour plus looking at the regex docs, to figure out how to do something using a regex. PHP’s trim() can do what I’m proposing, BTW.

1 Like

Well, the default is whitespace, which would remain the same.

@TimStreater This feature has been implemented if you haven’t already seen this:

1 Like

I rarely expect features to get back ported to older releases. There may be exceptions, but they are just that – exceptions. In the meantime, it should not be that hard to whip up your own that works as far back as you need it to work. A regex pattern would really maximize capability but would be somewhat slower in a loop with lots of iterations.

Or code it with exactly the same syntax as the upcoming feature (but a different method name) and use it for now and have an easy swap out to the internal function once there.

Function TrimStuff (Extends s As String, ParamArray stuff() As String) As String
  // Be on the safe side
  for pos as integer = 0 to stuff.LastRowIndex
    stuff( pos ) = stuff( pos ).ReplaceAllBytes( "\E", "\E\\E\Q" )

  var pattern as string = "(\Q" + String.FromArray( stuff, "\E|\Q" ) + "\E)\z"
  var rx as new RegEx
  rx.SearchPattern = pattern
  return rx.Replace( s )
End Function

(Off the top of my head and untested.)


I just realized, this is a TrimRight function, not Trim. It could be easily converted, but I’ll leave that others since it is really just an academic exercise.

1 Like