JavaScript中Replace的用法-DESTLIVE

javascript中replace的使用方法其实还是有很多种的,这里先讲一下常规替换的使用方法。

javascript中replace默认替换是只替换找到的第一个类似的匹配字段,如下:

<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))
</script>

输出效果如下:

Visit W3School!

要想全部替换则需要使用正则表达式来完成,如下:

<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, "W3School"))
</script>

输出效果如下:

Welcome to W3School! We are proud to announce that W3School
has one of the largest Web Developers sites in the world.