|
Globally replace text using just 5 lines of VBScript
If you've ever tried to implement a text search and replace function in an ASP page,
you probably resorted to lengthy parsing loops that used Instr() and an entire
host of string functions. If so, you'll be glad to know that there's a much easier way.
With the advent of VBScript 5.0, (IIS 5.0) Microsoft introduced the Regular
Expression engine. If you've used Perl or JavaScript, you may be familiar with
these pattern-matching powerhouses. In a nutshell, regular expressions let you
define a pattern, literal or representative, which you can then match against a second
string. For example, the literal pattern 'abc' as a regular expression would
find a match in 'dabcef', 'abcdef', or 'defabc'. To further refine a regular expression,
the Regular Expression engine offers a host of special me tacharacters,
similar to wildcard characters. For example, using these metacharacters, you could
search for any word that began with a letter and ended in a digit. To view
these metacharacters and their uses, visit
http://msdn.microsoft.com/scripting/default.htm
then search in the VBScript documentation for the RegExp object's Pattern
property. (If you don't have IIS 5.0, all you really need is the latest
version of VBScript, which you can download from
http://www.microsoft.com/msdownload/vbscript/scripting.asp
To create a simple find and replace subroutine with client-side VBScript, first create a RegExp object, like so
<script language="VBScript">
Sub GoReplace()
Set myReg = new RegExp
Next, set the object's properties.
myReg.IgnoreCase = True
myReg.Global = True
myReg.Pattern = "abc"
Here, we've used a literal string to create a global, case-insensitive pattern. Finally, you execute the object's Replace
method on a target string, as in
document.all.myTextArea.value = myReg.Replace(document.all.myTextArea,
"def")
End Sub
</script>
That's *all* there is to it! This example would replace "abc" with "def" wherever it
occurred within myTextArea. To execute the replace
on the first matching string only, set the Global property to False.
|