基于包含两个单独句子的text
变量,我想使用innerHTML
方法并将一组spans
添加到容器
中,如下所示:
null
const text = "this is, the [or here] first one. / this is the |second string is colored| (in here) |one| after this.";
const result = `
<span class="string">this is, the</span>
<span class="box-bracket">[</span>
<span class="string"> or here </span>
<span class="box-bracket">]</span>
<span class="string"> first one.</span>
<span class="separator"> / </span>
<span class="string"> this is the</span>
<span class="colored"> second string is colored </span>
<span class="round-bracket">(</span>
<span class="string"> in here </span>
<span class="round-bracket">)</span>
<span class="colored"> one</span>
<span class="string"> after this.</span>
`;
const container = document.getElementById("container");
container.innerHTML = result;
.box-bracket { color: #ff8800; }
.separator { color: #00e366; }
.colored { color: #1e00e3; }
.round-bracket { color: #e300d4; }
<div id ="container"></div>
null
到目前为止,我手动创建了result
,以向您显示我希望的结果,但我希望在代码中动态地创建result
。
正如您所看到的,有4种不同的颜色用于分隔符(只有一个分隔符),括号和彩色文本,该文本是困在符号之间的字符串的一部分。
我试了很多,但作为一个初学者,我想我需要有人帮忙才能找到一个好的解决办法。
唯一的条件是,这里可能没有任何符号和符号,就像一根简单的弦一样。。。在这种情况下我们没有任何改变。。。
const text = "this is, the [or here] first one. / this is the |second string is colored| (in here) |one| after this.";
const result = `
<span>this is,</span>
<span> the </span>
<span>[</span>
<span> or here </span>
<span>]</span>
<span> first</span><span> one.</span>
<span> / </span>
<span> this is the</span>
<span > second string is colored </span>
<span class="round-bracket">(</span>
<span> in here </span>
<span>)</span>
<span > one</span>
<span> after this.</span>
`;
const container = document.getElementById("container");
container.innerHTML = result;
const results = container.querySelectorAll("span");
const resultClasses = [
".box-bracket { color: #ff8800; }",
".separator { color: #00e366; }",
".colored { color: #1e00e3; }",
".round-bracket { color: #e300d4; }"
]
for(let i=0;i<results.length;i++){
results[i].classList.add(resultClasses[Math.floor(Math.random()*4)]);
}
我认为您可以使用.replace()
和每个选项的常规表达式。
null
const text = "this is, the [or here] first one. / this is the |second string is colored| (in here) |one| after this.";
const regexp1 = /\[/gm;
const regexp2 = /\]/gm;
let result = text.replace(regexp1,"<span class='box-bracket'>[</span>");
result = result.replace(regexp2,"<span class='box-bracket'>]</span>")
const container = document.getElementById("container");
container.innerHTML = result
.box-bracket { color: #ff8800; }
.separator { color: #00e366; }
.colored { color: #1e00e3; }
.round-bracket { color: #e300d4; }
<div id ="container"></div>