javascript - 如何从 JavaScript 中奇偶索引中的字符串替换特定部分?
问题描述
如何从 JavaScript 中奇偶索引中的字符串替换特定部分?
我想替换1, 3, 5, etc
```
with<span class="styles">
和2, 4, 6, etc
```
with </span>
。这样我就可以对这些区域进行样式设置。
它有点类似于Stack Overflow 的 Textarea/answer&question area或GitHub 的 editor。
例如,我有一个字符串:
const str = "Almost ```before``` we knew it, ```we``` had left the ```ground```.";
当我将它打印在页面上时,我想要它有点像这样。
Almost <span class="styles">before</span> we knew it, <span class="styles">we</span> had left the <span class="styles">ground</span>.
我研究了很多,但我只能```
从字符串中提取它,我不知道如何替换奇偶模式。
任何帮助,将不胜感激。
解决方案
您可以使用非贪婪搜索在分隔符之间搜索一个组,并在周围使用带有新标签的组。
const
string = "Almost ```before``` we knew it, ```we``` had left the ```ground```.",
result = string.replace(/```(.*?)```/g, '<span class="styles">$1</span>');
console.log(result);
推荐阅读
- vuejs2 - vue-owl-carousel 不适用于 v-for
- sql - 下面的 SQL 查询是否有效?
- python - 字典映射返回楠
- applescript - 在标记后取 X 符号并保存到 AppleScript 中的变量
- amazon-web-services - 从 aws cloudwatch 中删除自定义指标
- json - jq 如果元素存在则输出真
- amazon-web-services - Amazon LEX - 插槽类型,可以接受超过 140 个字符
- c++ - Arduino Softwareserial 说向量的多重定义
- arrays - 获取查询的最后一个元素后合并数组
- django - 通过用户字段添加到序列化程序