gpt4 book ai didi

javascript - 仅将颜色应用于数组的一部分?

转载 作者:行者123 更新时间:2023-11-30 15:26:40 25 4
gpt4 key购买 nike

我将从 other question 中复制一个数组为此:

console.log(arrayStr);

哪些输出:

(a) - text1, (b) - text2, (c) - text3, (d) - text3

如何将颜色应用到 (a) (b) 等部件?

正则表达式为:/\([^)]+\)/g;

谢谢。

最佳答案

为此,您可以扩展正则表达式以捕获一个组。然后,您可以使用它将匹配的 (X) 值包装在 span 元素中,您可以对其应用一些 CSS。试试这个:

$('div').html(function(i, html) {
return html.replace(/(\([^)]+\))/g, "<span>$1</span>");
})
span { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>(a) - text1, (b) - text2, (c) - text3, (d) - text3</div>

这是一个原生 JS 实现:

var el = document.getElementById('foo');
el.innerHTML = el.innerHTML.replace(/(\([^)]+\))/g, "<span>$1</span>");
span { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">(a) - text1, (b) - text2, (c) - text3, (d) - text3</div>

关于javascript - 仅将颜色应用于数组的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42857678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com