美文网首页
JavaScript字符串替换——replace()

JavaScript字符串替换——replace()

作者: MC桥默 | 来源:发表于2019-11-03 16:35 被阅读0次

replace()

定义与用法

replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
语法:stringObject.replace(regexp/substr,replacement)


replace()方法.png
返回值

一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或所有匹配之后得到的。

实例1

在本例中,我们将使用 "W3School" 替换字符串中的 "Microsoft":

<script type="text/javascript">

var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))

</script>

输出:

Visit W3School!

注:参数里面的字符串也可以用引号括起来

实例2

在本例中,我们将执行一次全局替换,每当 "Microsoft" 被找到,它就被替换为 "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.
实例3

您可以使用本例提供的代码来确保匹配字符串大写字符的正确:

text = "javascript Tutorial";
text.replace(/javascript/i, "JavaScript");

相关文章

网友评论

      本文标题:JavaScript字符串替换——replace()

      本文链接:https://www.haomeiwen.com/subject/hqbcbctx.html