JavaScript 替换字符串

在 JavaScript 中,如果想要替换字符串的一部分,常用的有以下 2 种方法。

  • replace()。
  • replaceAll()。

使用 replace() 替换字符串

在 JavaScript 中,我们可以使用 replace() 方法来将当前字符串的 “子串” 替换成 “另一个字符串”。

语法:

str.replace(searchValue, newValue)

说明:

replace() 方法接收以下 2 个参数。

  • searchValue(必选):指定子串或正则表达式。
  • newValue(必选):表示使用哪个字符串来代替。

str.replace(searchValue, newValue) 其实很好理解,它表示先根据 searchValue 来匹配出字符串中符合的子串,然后再使用 newValue 来替换这些子串。

示例 1:replace() 替换 “第一次” 匹配的子串

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <script>
        const str = "red green blue red";
        const result = str.replace("red", "orange");
        console.log(result);
    </script>
</body>
</html>

运行结果如下。

orange green blue red

分析:

当 searchValue 是一个字符串时,replace() 默认只会替换找到的第一个匹配项。这也是 replace() 最重要的特性之一。

如果想要替换所有匹配项,此时需要借助正则表达式以及 “g” 参数来实现,请看下面例子。

示例 2:replace() 替换 “所有” 匹配的子串

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <script>
        const str = "red green blue red";
        const result = str.replace(/red/g, "orange");
        console.log(result);
    </script>
</body>
</html>

运行结果如下。

orange green blue orange

分析:

/red/g 是一个正则表达式,表示替换字符串中所有的 "red" 子串。如果把 “g” 去掉,此时只会替换第一个匹配的 "red" 子串。

提示: 关于 replace() 更详细的用法,另请参阅:JavaScript 字符串 replace() 方法

使用 replaceAll() 替换字符串

为了解决 replace() 默认不进行全局替换的痛点,ES2021 (ES12) 引入了 replaceAll() 方法,它可以在不使用正则表达式的情况下,直接替换所有匹配的子字符串。

语法:

str.replaceAll(searchValue, newValue)

说明:

replaceAll() 方法接收以下 2 个参数。

  • searchValue(必选):指定子串或正则表达式。
  • newValue(必选):表示使用哪个字符串来代替。

示例 3:replaceAll() 替换所有匹配项

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <script>
        const str = "red green blue red";
        const result = str.replaceAll("red", "orange");
        console.log(result);
    </script>
</body>
</html>

运行结果如下。

orange green blue orange

分析:

对于这个例子来说,下面两种写法是等价的。

// 写法 1
str.replace(/red/g, "orange");

// 写法 2
str.replaceAll("red", "orange");

提示: 关于 replaceAll() 更详细的用法,另请参阅:JavaScript 字符串 replaceAll() 方法

给站长反馈

绿叶网正在不断完善中,小伙伴们如果发现任何问题,还望多多给站长反馈,谢谢!

邮箱:lvyenet@vip.qq.com

「绿叶网」服务号
绿叶网服务号放大
关注服务号,微信也能看教程。
绿叶网服务号