Selecting a Random File from a Directory and Outputting its Contents Demo

This demo illustrates how to have a random text file read from a directory and have its contents displayed. Below you will see the output of a random text file from the directory of (very) old WebWeekly issues.

WebDaily: Your daily source for Web Technology Tips and Tricks!

Formatting with JavaScript

* This article discusses how to format strings and numbers using JavaScript.

Since Internet Explorer is the only browser which supports VBScript, whendeveloping client-side scripts, using JavaScript is imperative. JavaScript,though, lacks the easy to use formatting features that VBScript inherentlyprovides. There are often times, though, when you need to use JavaScript tooutput dynamic values to form elements, or through alerts, and you mustuse JavaScript's formatting features. This article intends to step throughsome of the techniques you can use in JavaScript to format numbers andstrings.

One nice thing about VBScript is its FormatNumber function. Using thisfunction you can specify how to display a number, and how many decimalplaces to use, if a leading zero is to be included for fractional numbers,and if you wish to use parenthesis for negative numbers. Let's write thisfunction in JavaScript:

   function FormatNumber(num, decimalNum, bolLeadingZero, bolParens)   /* IN - num:            the number to be formatted           decimalNum:     the number of decimals after the digit           bolLeadingZero: true / false to use leading zero           bolParens:      true / false to use parenthesis for - num      RETVAL - formatted number   */   {       var tmpNum = num;       // Return the right number of decimal places       tmpNum *= Math.pow(10,decimalNum);       tmpNum = Math.floor(tmpNum);       tmpNum /= Math.pow(10,decimalNum);       var tmpStr = new String(tmpNum);       // See if we need to hack off a leading zero or not       if (!bolLeadingZero && num < 1 && num > -1 && num !=0)           if (num > 0)               tmpStr = tmpStr.substring(1,tmpStr.length);           else               // Take out the minus sign out (start at 2)               tmpStr = "-" + tmpStr.substring(2,tmpStr.length);                               // See if we need to put parenthesis around the number       if (bolParens && num < 0)           tmpStr = "(" + tmpStr.substring(1,tmpStr.length) + ")";       return tmpStr;   }

This function should suit most of your number formatting needs (except forcurrency issues). This function could be made a little more fail-safe ifsome priliminary testing was implemented. For example, if decimalNum isless than zero, then we must handle it so not to get a strange result. Hereis an example of how you could use the function above:

var MyNum = -0.314159;

This would print (.314) as your output.

With a little ingenuity and code, you can create any string formattingfunction by knowing just the following two string operators: substring andindexOf. To use any of the string object method or properties, you mustcreate a variable of type String. In the FormatNumber function, I createda variable named tmpStr which was declared as follows:

var tmpStr = new String();

Once you declare a variable as a String object, you can use the appropriatemethods. One important method is indexOf. indexOf returns a cbaracter ata passed in position of your string. For example:

tmpStr = String("Hello world!");

would output "o". One important thing to remember about strings in JavaScriptis that they are zero-based. The first character in a string is in thezero-th position. So tmpStr.indexOf(4) returns the 5th character, which is"o". The other important string object method, substring, takes twoparameters, the start and stop positions. Let's look at a quick example:

tmpStr = String("Hello world!");

would output "o wor". Again, recall that strings are indexed starting atzero, not one. By just using substring and indexOf, you can formulate anystring formatting functions. Examples can be seen at the 4 Guys website,

Happy Programming!

To subscribe to WebDaily, point your browser to:

Please forward this information to a friend, including thesubscription URL! Happy Programming!

Source Code
Option Explicit

Function ReadDir(FolderName)
	On Error Resume Next
	Dim objFSO
	Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
	'Make sure the specified folder exists
	If Not objFSO.FolderExists(FolderName) Then
		ReadDir = "Folder does not exist. <br><b>This can be changed to " & _
				"a default message or nothing.</b>"
		Exit Function
	End If

	Dim objFolder
	Set objFolder = objFSO.GetFolder(FolderName)

	Dim I : I = -1
	ReDim arrFile(20)
	Dim objFile
	For Each objFile In objFolder.Files
		If Right(objFile, 4) = ".txt" Then
  			I = I + 1
			if I > UBound(arrFile) then ReDim Preserve arrFile(I + 20)
			arrFile(I) = objFile.Path
		End If
	'Make sure arrFile is the right size
	Redim Preserve arrFile(I)

    If I = -1 Then
		ReadDir = "No text files in this directory. <br><b>This can be " & _
		          "changed to a default message or nothing.</b>"
		Exit Function
	End If

	Dim RanFile : RanFile = Int((UBound(arrFile) - 1 + 1) * Rnd + 1)
	Dim strOutput : strOutput = ""
	Dim strFileName : strFileName = arrFile(RanFile)
	If objFSO.FileExists(strFileName) Then
		Dim objTextStream
		Set objTextStream = objFSO.OpenTextFile(strFileName, 1)
			Do While Not objTextStream.AtEndOfStream
				strOutput = strOutput & objTextStream.ReadLine
		ReadDir = "File does not exist. <br><b>This can be changed to a " & _
		          "default message or nothing.</b>"
		Exit Function
	End If
    ReadDir = strOutput
 Set objTextStream = Nothing
 Set objFolder = Nothing
 Set objFile = Nothing
 Set objFSO = Nothing
End Function

<h1>Selecting a Random File from a Directory and Outputting its Contents Demo</h1>


[Return to the User Tip]