首页 > 解决方案 > 如何从 JavaScript 中奇偶索引中的字符串替换特定部分?

问题描述

如何从 JavaScript 中奇偶索引中的字符串替换特定部分?


我想替换1, 3, 5, etc ```with<span class="styles">2, 4, 6, etc ```with </span>。这样我就可以对这些区域进行样式设置。

它有点类似于Stack Overflow 的 Textarea/answer&question areaGitHub 的 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>.

我研究了很多,但我只能```从字符串中提取它,我不知道如何替换奇偶模式。

任何帮助,将不胜感激。

标签: javascripthtmlcssstringreplace

解决方案


您可以使用非贪婪搜索在分隔符之间搜索一个组,并在周围使用带有新标签的组。

const
    string = "Almost ```before``` we knew it, ```we``` had left the ```ground```.",
    result = string.replace(/```(.*?)```/g, '<span class="styles">$1</span>');

console.log(result);


推荐阅读