VBScript ReplaceFunction


VBScript 参考手册Complete VBScript Reference

The Replace function replaces a specified part of a string with another string a specified number of times.

Syntax

Replace(string,find,replacewith[,start[,count[,compare]]])

Parameter Description
string Required. The string being searched.
find Required. The part of the string to be replaced.
replacewith Required. The substring used for replacement.
start Optional. The specified starting position. The default value is 1. All characters before the starting position will be removed.
count Optional. Specifies the number of replacements to perform.
The default value is -1, which means all possible replacements are performed.
compare Optional. Specifies the type of string comparison to use. The default is 0.

The following values can be used:

  • 0 = vbBinaryCompare - Performs a binary comparison
  • 1 = vbTextCompare - Performs a text comparison

Examples

Example 1

Replace the word "beautiful" with "fantastic":

<script type="text/vbscript">

txt="This is a beautiful day!"
document.write(Replace(txt,"beautiful","fantastic"))

</script>

The output of the above example is:

This is a fantastic day!

Try it yourself »

Example 2

Replace the letter "i" with "##":

<script type="text/vbscript">

txt="This is a beautiful day!"
document.write(Replace(txt,"i","##"))

</script>

The output of the above example is:

Th##s ##s a beaut##ful day!

Try it yourself »

Example 3

Replace the letter "i" with "##", starting from position 15:

Please note that all characters before position 15 will be removed.

<script type="text/vbscript">

txt="This is a beautiful day!"
document.write(Replace(txt,"i","##",15))

</script>

The output of the above example is:

t##ful day!

Try it yourself »

Example 4

Starting from position 1, replace the first 2 letters "i" with "##":

<script type="text/vbscript">

txt="This is a beautiful day!"
document.write(Replace(txt,"i","##",1,2))

</script>

The output of the above example is:

Th##s ##s a beautiful day!

Try it yourself »

Example 5

Replace the letter "t" with "##", using text and binary comparison:

<script type="text/vbscript">

txt="This is a beautiful day!"
document.write(Replace(txt,"t","##",1,-1,1) & "<br />")
document.write(Replace(txt,"t","##",1,-1,0))

</script>

The output of the above example is:

##his is a beau##iful day!
This is a beau##iful day!

Try it yourself »

VBScript 参考手册Complete VBScript Reference Other Extensions