replace方法js
时间: 2023-06-22 07:34:55 浏览: 75
JavaScript 中的replace方法说明
JavaScript中的replace()方法用于替换字符串中的文本。该方法接受两个参数:要替换的文本和替换的文本。
例如,要将字符串中的所有"apple"替换为"orange",可以使用以下代码:
```
let str = "I have an apple. My friend also has an apple.";
let newStr = str.replace("apple", "orange");
console.log(newStr); // 输出: "I have an orange. My friend also has an apple."
```
如果要替换所有出现的"apple",则可以使用正则表达式:
```
let str = "I have an apple. My friend also has an apple.";
let newStr = str.replace(/apple/g, "orange");
console.log(newStr); // 输出: "I have an orange. My friend also has an orange."
```
在这个例子中,/apple/g表示全局替换,即替换所有出现的"apple"。
阅读全文