[Classic ASP] Improving split function

Coming from the JavaScript world, I’m used to split function working as follow :

"".split(",")
> Array [ "" ]

It’s basic JavaScript. Take an empty string, try to split it on a delimiter, it will return an array containing just one element : an empty string. It’s exactly what you expect from the function, always return an array. Like it should be in every programming language.

A few weeks ago, I had to deal with split function in ASP Classic. Calling the function is a bit different, but that’s not a big deal :

split("foo,bar", ",")

The function works fine in almost every cases. But it has an unexpected behaviour when you use it on an empty string. Let’s try it :

Dim array
array = split("", ",")
'-- Expect array to contain one element
UBound(array) '-- Returns -1. Wait! What?
array(0)      '-- Guess what: Internal server error

That’s a problem. The split function does not return an array containing an empty string when you try to split an empty string, it just returns an array with nothing in it – hence UBound returning -1.

When you are aware of this particularity, it’s easier to write your code. Since I personally prefer a JavaScript-like split function, I decided to write a betterSplit function doing the job as I wanted :

'-- Improve Split to work as expected
Function betterSplit(str, delimiter)
  Dim ar
  ar = Split(str, delimiter)

  '-- UBound
  '-- < 0 if empty string
  '-- = 0 if no delimiter in string
  If UBound(ar) <= 0 Then
    ReDim ar(0)
    ar(0) = str
  End If

  betterSplit = ar
End Function

As a matter of fact, I find this function much better than the original split function as it always returns an array even when using an empty string as a parameter.

Anonyme

Auteur/autrice : Victor

Ingénieur en informatique de formation et de métier, j’administre ce serveur et son domaine et privilégie l'utilisation de logiciels libres au quotidien. Je construis progressivement mon "cloud" personnel service après service pour conserver un certain contrôle sur mes données numériques.

Une réflexion sur « [Classic ASP] Improving split function »

Répondre à Adam Annuler la réponse

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *