angular string.replace(t, (s)=> {}) 方法
时间: 2024-03-11 14:47:26 浏览: 20
`String.prototype.replace()` 方法是用于替换字符串中的某些字符或者字符串的方法,可以传递一个正则表达式或者字符串作为被替换的部分。在传递正则表达式时,可以使用第二个参数传递一个函数作为替换部分,该函数的第一个参数是与正则表达式匹配的子字符串,而第二个参数是与正则表达式中的捕获组匹配的字符串。
示例:
```javascript
const str = "hello world";
// 使用正则表达式来替换字符串中的 "world" 为 "universe"
const newStr = str.replace(/world/, "universe");
console.log(newStr); // Output: "hello universe"
// 使用函数来替换字符串中的 "world" 为 "universe"
const newerStr = str.replace(/world/, (match) => {
return "universe";
});
console.log(newerStr); // Output: "hello universe"
```
在上面的例子中,我们使用 `replace()` 方法来将字符串 `str` 中的 "world" 替换为 "universe"。首先,我们使用字符串 "universe" 来替换 "world",这个替换是直接替换的。然后,我们使用一个函数来替换 "world",这个函数接收一个参数,即与正则表达式匹配的子字符串,然后返回 "universe",这个替换是动态的。