首页 > 解决方案 > 在两个之间更改字符串的颜色 | 符号

问题描述

我们如何改变|给定字符串中两个符号之间的字符串颜色:

这是原型:

const string = "Starting |this should be colored| there may be more |colored too|";

let result; // save spans here 
result = string; // remove this 

const container = document.getElementById("container");
container.innerHTML = result;
.colored { color: #1e00e3; }
<div id ="container"></div>

编辑:这不是基本的,你应该选择带和不带 | 的字符串。符号,因为我们只想要字符串而不是符号......

标签: javascripthtmlcss

解决方案


这可以使用 String.prototype.replace()来完成

const string = "Starting |this should be colored| there may be more |colored too|";
const result = string.replace(/\|\b([^|]+)\b\|/g, `<span class="colored">$1</span>`);

const container = document.querySelector("#container");
container.innerHTML = result;
.colored { color: #1e00e3; }
<div id ="container"></div>

或者也可以使用函数:

string.replace(/\|\b([^|]+)\b\|/g, (fullMatch, group1) => {
  return `<span class="colored">${group1}</span>`
});

这是上例中正则表达式的Regex101 链接。

另一个例子:


推荐阅读