Definition and Usage
|
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 必选项。指定所要替换的字符串的新值 |
Tips and Notes
注意
Note: The replace() method is case sensitive.
注意:replace()方法是精确匹配的
Example 1 - Standard Replace
实例 1 - 标准替换
In the following example we will replace the word Microsoft with w3pop:
在下面的例子中,我们将把Microsoft替换成w3pop:
<script type="text/javascript"> var str="这里是Micosoft!" </script> |
The output of the code above will be:
输出结果为:
这里是w3pop! |
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! |
Example 2 - Case-insensitive Search
实例 2 - 模糊匹配
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:
返回结果为:
这里是w3pop! |
Example 3 - Global Search
实例3 - 多次匹配
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, "w3pop")) </script> |
The output of the code above will be:
输出结果为:
欢迎来到w3pop! w3pop将为你提供全面的技术支持 |
Example 4 - Global and Case-insensitive Search
实例 4 - 多次模糊匹配
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, "w3pop")) </script> |
The output of the code above will be:
输出结果为:
欢迎来到w3pop! w3pop将为你提供全 |