当前位置: 首页 > 网络学院 > 客户端脚本教程 > JavaScript > JavaScript replace() 方法
The replace() method is used to replace some characters with some other characters in a string.
replace()方法用于将字符串中的一些字符替换成其他字符
stringObject.replace(findstring,newstring) |
Parameter 参数 | Description 注释 |
---|---|
findstring 目标字符串 | Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag 必选项。指定所要替换的字符串。要执行多次匹配需要添加一个”g“标记。要指定模糊匹配需要添加一个”i“标记 |
newstring 新字符串 | Required. Specifies the string to replace the found value from findstring 必选项。指定所要替换的字符串的新值 |
Note: The replace() method is case sensitive.
注意:replace()方法是精确匹配的
In the following example we will replace the word Microsoft with RuanChen:
在下面的例子中,我们将把Microsoft替换成RuanChen:
<script type="text/javascript"> var str="这里是Micosoft!" </script> |
The output of the code above will be:
输出结果为:
这里是RuanChen! |
Note: In the following example the word Microsoft will not be replaced (because the replace() method is case sensitive):
注意:在下面的例子中,Microsoft将不会被替换(replace()方法是精确匹配的)
<script type="text/javascript"> var str="这里是Microsoft!" </script> |
The output of the code above will be:
输出结果为:
这里是Microsoft! |
In the following example we will perform a case-insensitive search, and the word Microsoft will be replaced:
在下面的例子中,我们将演示一个模糊匹配,Microsoft将会被替换:
<script type="text/javascript"> var str="这里是Microsoft!" </script> |
The output of the code above will be:
返回结果为:
这里是RuanChen! |
In the following example we will perform a global match, and the word Microsoft will be replaced each time it is found:
在下面的例子中,我们将演示一个多次匹配:
<script type="text/javascript"> var str="欢迎来到Microsoft! " document.write(str.replace(/Microsoft/g, "RuanChen")) </script> |
The output of the code above will be:
输出结果为:
欢迎来到RuanChen! RuanChen将为你提供全面的技术支持 |
In the following example we will perform a global and case-insensitive match, and the word Microsoft will be replaced each time it is found, independent of upper and lower case characters:
在下面的例子中,我们将演示多次模糊匹配:
<script type="text/javascript"> var str="欢迎来到Microsoft! " document.write(str.replace(/microsoft/gi, "RuanChen")) </script> |
The output of the code above will be:
输出结果为:
欢迎来到RuanChen! RuanChen将为你提供全面的技术支持 |
replace()
How to use replace() to replace some characters in a string.
如何用replace()来替换字符串中的字符
replace() Case-insensitive search
How to use replace() with the 'i' flag to replace some characters in a string.
如何用replace()和"i"标记来模糊替换字符串中的字符
replace() Global search
How to use replace() with the 'g' flag to replace some characters in a string.
如何用replace()和”g“标记来多次替换字符串中的字符