用js实现 // 2, 假设有一个多字符的片断重复出现,把"really"、"really really ",以及任意数量连续出现的"really"字符串换成一个简单的"very ” // ( Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard )
时间: 2024-01-29 15:04:49 浏览: 63
可以使用正则表达式和replace方法来实现:
```javascript
const str = "Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard";
const result = str.replace(/(really\s)+/g, "very ");
console.log(result); // "Billy tried very hard Sally tried very hard Timmy tried very hard Johnny tried very hard"
```
正则表达式`(really\s)+`匹配重复出现的"really"字符串,`\s`表示空格。使用g标志表示全局匹配,将所有匹配的字符串替换为"very "。最终输出结果为"Billy tried very hard Sally tried very hard Timmy tried very hard Johnny tried very hard"。
阅读全文