HOWTO: vbScript: Remove Chr(0) (null) from a string

I hit a problem the other day, writing some log code to monitor activity on a website and in the database. Part of this monitoring process looked at the locks in MSSQL and when it spotted some locks, wrote them to a log. The problem I encountered was that the "waitresource" column contains some non-printable characters. Specifically, I was using Rtrim(rs("waitresource")) to trim the excess of what appeared to be trailing white space, and this appeared to do the trick. However on closer examination of the log file, I could see that a trailing null (char 0) was being written to the log file after the waitresource text. This was causing problems for some other code that was reading the log file. So how to get rid of this unwanted null character?

This is the solution I came up with:

Function CLEAN(s)
  Dim re
  Set re = New RegExp
  re.Global = True
  re.Pattern = "[\0]"   ' should see backslash zero inside the square braces
  CLEAN = re.Replace(s,"")
  Set re = Nothing
End Function

So I now just wrap my Rtrim(rs(“waitresource”)) with CLEAN() to get a null free string:


About austinfrance

Technical Developer @ RedSky IT / Explorer Software
This entry was posted in vbScript. Bookmark the permalink.

One Response to HOWTO: vbScript: Remove Chr(0) (null) from a string

  1. oscarsnr says:

    Really good, works as described. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s