

注意:ECMAScript v3 规定,replace() 方法的参数 replacement 可以是函数而不是字符串。在这种情况下,每个匹配都调用该函数,它返回的字符串将作为替换文本使用。该函数的第一个参数是匹配模式的字符串。接下来的参数是与模式中的子表达式匹配的字符串,可以有 0 个或多个这样的参数。接下来的参数是一个整数,声明了匹配在 stringObject 中出现的位置。最后一个参数是 stringObject 本身。
实例
例子 1
在本例中,我们将使用 "W3School" 替换字符串中的 "Microsoft":
<script type="text/javascript">var str="Visit Microsoft!"document.write(str.replace(/Microsoft/, "jb51"))</script>输出:Visit jb51!
<script type="text/javascript">var str="Welcome to Microsoft! "str=str + "We are proud to announce that Microsoft has "str=str + "one of the largest Web Developers sites in the world."document.write(str.replace(/Microsoft/g, "jb51"))</script>输出:
text = "javascript Tutorial";text.replace(/javascript/i, "JavaScript");输出:javascript Tutorial
name = "Doe, John";name.replace(/(w+)s*, s*(w+)/, "$2 $1");输出:John Doe
name = ""a", "b"";name.replace(/"([^"]*)"/g, ""$1"");输出:"a", "b"
name = "aaa bbb ccc";uw=name.replace(/w+/g, function(word){ return word.substring(0,1).toUpperCase()+word.substring(1);} );输出:Aaa Bbb Ccc