Javascript replace

PHPABC JavaScript 709 次浏览 , 没有评论

The replace() method is used to replace some characters with some other characters in a string.
replace()方法用于将字符串中的一些字符替换成其他字符

Syntax
语法
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 test:
在下面的例子中,我们将把Microsoft替换成test:

<script type="text/javascript">var str="这里是Micosoft!"document.write(str.replace(/Microsoft/, "test"))</script>

The output of the code above will be:
输出结果为:

这里是test!

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!"document.write(str.replace(/microsoft/, "test"))</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!"document.write(str.replace(/microsoft/i, "test"))</script>

The output of the code above will be:
返回结果为:

这里是W3Schools!

——————————————————————————–

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! "str=str + "Microsoft将为你提供全面的技术支持"document.write(str.replace(/Microsoft/g, "test"))</script>

The output of the code above will be:
输出结果为:

欢迎来到test! test将为你提供全面的技术支持

——————————————————————————–

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! "str=str + "Microsoft将为你提供全面的技术支持"document.write(str.replace(/microsoft/gi, "test"))</script>

The output of the code above will be:
输出结果为:

欢迎来到test! test将为你提供全面的技术支持

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Go