Search a VBScript Array with Filter()

Use Filter() in Classic ASP to search a one-dimensional VBScript array of strings. It returns a new array containing values that include, or exclude, a substring. The original array is not changed.

Quick example: find matching array values

Dim countries, matches
countries = Array("UK", "USA", "Canada", "UAE")
matches = Filter(countries, "UA")
Response.Write Join(matches, ", ")

Output:

UAE

The search text "UA" appears inside "UAE" but not the other country names. Use Join() when you want to display the matching elements as a single string.

Filter() syntax and parameters

Filter(sourceArray, match [, include [, compare]])

The sourceArray argument is a one-dimensional string array. Filter() searches each element for the text in match; it is a substring search, not an exact-value search.

ArgumentRequired?Meaning
sourceArrayYesA one-dimensional array of strings, for example Array("UK", "USA", "UAE").
matchYesThe substring to search for within each array element.
includeNoTrue keeps matching elements (default). False keeps elements that do not contain the match.
compareNovbBinaryCompare (0) performs a binary comparison; vbTextCompare (1) performs a textual comparison.

If you specify the comparison mode, also provide the include argument. Name the comparison constant explicitly to make your code easier to read. For related examples, see StrComp() string comparison.

Complete example: search and display an array

This preserves the original example using four country names. Dim myArray(3) creates positions 0 through 3; the result of Filter() is a separate zero-based array.

Dim myArray(3), item, searchString, filtered
myArray(0) = "UK"
myArray(1) = "USA"
myArray(2) = "Canada"
myArray(3) = "UAE"

For Each item In myArray
    Response.Write Server.HTMLEncode(item) & "<br>"
Next

searchString = "UA"
filtered = Filter(myArray, searchString)

Response.Write "<br>-----After Filter------<br>"
For Each item In filtered
    Response.Write Server.HTMLEncode(item) & "<br>"
Next

Output:

UK
USA
Canada
UAE

-----After Filter------
UAE

The For Each loop prints the original values first and then the filtered results. Use Server.HTMLEncode() before inserting individual array values into HTML if their content may come from visitors or external data.

Include matches or exclude them

Keep matching items with True

Dim countries, matching
countries = Array("UK", "USA", "Canada", "UAE")
matching = Filter(countries, "U", True, vbBinaryCompare)
Response.Write Join(matching, ", ")

Output:

UK, USA, UAE

The include parameter defaults to True. Specify it when you want the purpose of the code to be explicit.

Exclude matching items with False

Dim countries, notMatching
countries = Array("UK", "USA", "Canada", "UAE")
notMatching = Filter(countries, "UA", False, vbBinaryCompare)
Response.Write Join(notMatching, ", ")

Output:

UK, USA, Canada

When include is False, elements containing "UA" are removed from the returned array. The original countries array is unchanged.

Binary and text comparisons

Use vbBinaryCompare for case-sensitive matching and vbTextCompare for case-insensitive matching. The spelling of the source values remains unchanged in either result.

Dim words, binaryMatches, textMatches
words = Array("ASP", "aspnet", "Classic ASP", "HTML")
binaryMatches = Filter(words, "asp", True, vbBinaryCompare)
textMatches = Filter(words, "asp", True, vbTextCompare)

Response.Write "Binary: " & Join(binaryMatches, ", ") & "<br>"
Response.Write "Text: " & Join(textMatches, ", ")

Output:

Binary: aspnet
Text: ASP, aspnet, Classic ASP
ComparisonSearchMatched values
vbBinaryCompare"asp"aspnet
vbTextCompare"asp"ASP, aspnet, Classic ASP

For a reusable case-insensitive search, use the same expression as in the original tutorial:

filtered = Filter(myArray, searchString, True, vbTextCompare)

Text comparison may depend on language and regional rules. When the matching behavior matters, specify the comparison mode instead of relying on defaults. See UCase() and LCase() for changing the case of strings themselves.

What happens when there are no matches?

If no element contains the search text, Filter() returns an empty array. For Each safely processes its items without requiring an array index; no loop body executes when there are no values.

Dim fruits, matches, item, count
fruits = Array("Apple", "Banana", "Cherry")
matches = Filter(fruits, "xyz", True, vbTextCompare)
count = 0

For Each item In matches
    count = count + 1
    Response.Write Server.HTMLEncode(item) & "<br>"
Next
If count = 0 Then
    Response.Write "No matching items found."
End If

Output:

No matching items found.

Avoid immediately reading matches(0) when the result might be empty. For general information about indexes and dimensions, see array size with UBound() and LBound().

Searching for an empty substring

An empty search string is not a useful search term for most interfaces. Validate user input with Trim() and Len() before calling Filter(), instead of treating an empty search as a meaningful filter.

Dim searchText
searchText = Trim("   ")
If Len(searchText) = 0 Then
    Response.Write "Enter a search term."
End If

Practical Filter() examples

Filter filenames by extension

The function searches for a substring anywhere in each element, so ".asp" also matches names such as "index.asp.bak". For a strict extension check, use Right() or other filename-aware logic.

Dim files, aspFiles
files = Array("index.asp", "form.asp", "photo.jpg", "index.asp.bak")
aspFiles = Filter(files, ".asp", True, vbTextCompare)
Response.Write Server.HTMLEncode(Join(aspFiles, ", "))

Output:

index.asp, form.asp, index.asp.bak

Split a string, filter the array, and join the results

Combine Split(), Filter() and Join() to narrow a list without writing a separate search loop.

Dim sourceText, values, matching
sourceText = "red,green,blue,grey,gold"
values = Split(sourceText, ",")
matching = Filter(values, "gr", True, vbTextCompare)
Response.Write Join(matching, " | ")

Output:

green | grey

Display matches as an HTML list

Build HTML tags separately and encode each data value, rather than inserting untrusted strings as markup.

Dim items, matches, item
items = Array("Apple", "Apricot", "Banana", "Avocado")
matches = Filter(items, "ap", True, vbTextCompare)

Response.Write "<ul>"
For Each item In matches
    Response.Write "<li>" & Server.HTMLEncode(item) & "</li>"
Next
Response.Write "</ul>"

Output:

• Apple
• Apricot

Filter() searches substrings, not exact values

A search for "pen" matches both "pen" and "pencil". When exact equality is required, loop through the array and use StrComp() to compare the entire string.

Dim products, product
products = Array("pen", "pencil", "blue pen", "paper")
For Each product In products
    If StrComp(product, "pen", vbTextCompare) = 0 Then
        Response.Write Server.HTMLEncode(product)
    End If
Next

Output:

pen

Filter an array using Classic ASP form input

This self-contained example reads a search term from a POST form, trims extra spaces, and displays matches. The list of allowed product names stays on the server; the visitor controls only the search term. For handling submitted values, see Classic ASP forms.

<form method="post" action="">
  <label for="search">Search a fruit:</label>
  <input type="text" id="search" name="search" required>
  <button type="submit">Find matches</button>
</form>
<%
Dim fruits, searchText, results, fruit, count
fruits = Array("Apple", "Banana", "Apricot", "Cherry")
If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
    searchText = Trim(Request.Form("search"))
    If Len(searchText) > 0 Then
        results = Filter(fruits, searchText, True, vbTextCompare)
        count = 0
        Response.Write "<ul>"
        For Each fruit In results
            Response.Write "<li>" & Server.HTMLEncode(fruit) & "</li>"
            count = count + 1
        Next
        Response.Write "</ul>"
        If count = 0 Then Response.Write "<p>No results found.</p>"
    Else
        Response.Write "<p>Please enter a search term.</p>"
    End If
End If
%>

For example, searching "ap" displays Apple and Apricot. The form is for learning and should run on a Classic ASP-enabled IIS server. Always validate and encode visitor-controlled values when displaying or storing them.

Common errors and troubleshooting

IssueExplanation or solution
Type mismatchPass a one-dimensional array of strings, not a single string or a multidimensional array. Avoid passing Null as the array value.
Unexpected extra matchesFilter() searches for a substring anywhere in each element. Use an exact comparison when necessary.
Uppercase and lowercase differencesPass vbTextCompare for a text comparison and vbBinaryCompare when case matters.
Result index errorA search can produce no results. Iterate with For Each or check whether results exist before indexing them.
All results excludedCheck the third argument: False returns items that do not contain the search string.
Special characters displayed as HTMLUse Server.HTMLEncode() for each returned value when rendering it in an HTML document.

Frequently asked questions

Does Filter() change the source array?

No. Filter() creates a separate result array; the source array keeps its original elements.

Can I use Filter() to find an exact word?

Not directly. It performs substring matching. Use StrComp() in a loop when you need an entire element to match.

Can Filter() exclude matching values?

Yes. Set the third argument to False, for example Filter(items, "test", False, vbTextCompare).

Does Filter() work with a two-dimensional array?

No. It expects a one-dimensional array of strings. Extract the values you need into a one-dimensional array first.

How can I display the matches in one line?

Use Join(Filter(items, "a", True, vbTextCompare), ", ") and HTML-encode the resulting text before displaying visitor-controlled data.

What is the difference between Filter() and InStr()?

Filter() returns matching elements from an array. InStr() returns the position of matching text inside one string.

For formal parameter definitions and comparison behavior, see the Microsoft Filter() function reference.

Back to top ↑


ASP Home






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer