(共566篇)
全部分类

替换字符串
[ JS基础 ] 

替换字符串

str.replace()方法在字符串中查找指定字符串,并替换为指定内容;返回替换后的新字符串。该方法有多种用法。

replace(pattern, newStr)

1
2
3
4
5
6
7
8
<script>
    var str = "welcome to china, welcome to china";
    console.log("替换前的str:", str);

    var res = str.replace("china", "usa");
    console.log("替换后的str:", str);
    console.log("替换后的返回值:", res);
</script>

代码案例

pattern为是字符串类型是,只会替换原字符串中从左到到右第一个与pattern相同的字符,比如上面案例中的第 2 个china,就没有被新字符串替换掉。

str.replace(pattern, fn(match, index, oldStr))

注意:这里函数接收的三个参数值,必须在pattern为字符串类型时才能使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<script>
    var str = "welcome to china, welcome to china";
    console.log("替换前的str:", str);

    var res = str.replace("china", function(match, index, oldStr) {
        console.log("匿名函数第1个参数的值:", match);
        console.log("匿名函数第2个参数的值:", index);
        console.log("匿名函数第3个参数的值:", oldStr);
        return "usa";
    });
    console.log("替换后的str:", str);
    console.log("替换后的返回值:", res);
</script>

代码案例

替换所有符合pattern的字符串

前面说只能替换符合pattern的第一批字符串,那么如何实现替换所有符合pattern的字符呢?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<script>
    var str = "welcome to china, welcome to china";
    console.log("替换前的str:", str);

    // 每替换一次,就把替换后的新字符串,赋值给str
    while (str.includes("china")) {
        str = str.replace("china", "usa");
    }
    console.log("替换后的str:", str);
    console.log("替换后的str:", str);
</script>

代码案例

案例中,每替换一次,就把替换后的新字符串,赋值给str。当str中不再包含china时,str.includes('china')的返回值为false,while 循环的条件为 false,自然就停止循环了。

使用do...while也可以实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<script>
    var str = "welcome to china, welcome to china";
    console.log("替换前的str:", str);

    do {
        str = str.replace("china", "usa");
    } while (str.includes("china"));

    console.log("替换后的str:", str);
    console.log("替换后的str:", str);
</script>

代码案例

使用正则表达式

正则表达式还没讲到,暂时先不讲使用正则表达式替换的方法