用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 17:04:49 浏览: 58
可以使用正则表达式和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"。
相关问题
js正则假设有一个多字符的片断重复出现,把"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 )
可以使用正则表达式和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 newStr = str.replace(/(really\s+)+/g, "very ");
console.log(newStr);
```
输出结果为:"Billy tried very hard Sally tried very hard Timmy tried very hard Johnny tried very hard"。
解释一下正则表达式的含义:
- `(really\s+)+`:匹配一个或多个重复出现的"really"字符串,每个字符串后面可能跟着一个或多个空格。
- `/g`:全局匹配模式,表示匹配所有符合模式的字符串。
- `"very "`:将匹配到的字符串替换成"very "。
在js中使用正则假设有一个多字符的片断重复出现,把"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 )
你可以使用正则表达式和 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 +/g, "very ");
console.log(result);
```
输出结果为:
```
Billy tried very hard Sally tried very hard Timmy tried very hard Johnny tried very hard
```
正则表达式 /really +/g 匹配一个或多个空格后面紧跟着 "really" 的字符串,并且全局匹配所有这样的字符串。replace() 方法将匹配到的字符串替换为 "very "。
阅读全文