【发布时间】:2021-05-03 20:04:46
【问题描述】:
我想使用 | , $ , ^ , # , @ 将跨度替换为特定的类样式,只在这样的字符串中签名:
const text = `|If I create a random| text or xml file, |they do| not |end up| being wrapped in html. I also $tried to$ disable $all the$ plugins and ^default^ layout ^settings^ as well as the If I #create# a random #text# or xml file, they @do not@ end up @being wrapped in html@.
I also tried to disable all the plugins and default layout settings as well as the`;
let render = '';
render += getColored(text);
document.getElementById('content').innerHTML = render;
function getColored(text) {
let result = text;
result = result.replace(/\|([^|]+)\|/g, '<span class="blue-string">$1</span>');
result = result.replace(/\$([^)]+)\$/g, '<span class="red-string">$1</span>');
result = result.replace(/\^([^+]+)\^/g, '<span class="orange-string">$1</span>');
result = result.replace(/\#([^+]+)\#/g, '<span class="purple-string">$1</span>');
result = result.replace(/\@([^+]+)\@/g, '<br><span class="ltr-string">$1</span>');
return result;
}
.blank {
display: inline-block;
border-bottom: 4px dotted red;
width: 150px;
}
.blue-string {
font-family: "Vazir";
color: #7e7cff;
display: inline-block;
text-shadow: 0px 0px 1px #010076;
}
.red-string {
font-family: "Vazir";
color: #ff005e;
display: inline-block;
text-shadow: 0px 0.5px 1px #e40053;
}
.orange-string {
font-family: "Vazir";
color: #ffb000;
display: inline-block;
text-shadow: 0px 0.5px 1px #b46a00;
}
.purple-string {
font-family: "Vazir";
color: #8805ff;
display: inline-block;
text-shadow: 0px 0.5px 1px #b46a00;
}
.ltr-string {
direction: ltr;
font-size: .9em;
color: #565559;
display: block;
}
<div id="content"></div>
如您所见,它仅适用于 | 符号,而其他符号会出现失真。
请注意,使用 /$([^)]+)$/g 代替 /|([^|]+)|/g 不能解决问题。
我该如何解决这个问题?
【问题讨论】:
标签: javascript html css regex