首页 > 解决方案 > 更改 [ ] 符号之间的样式的问题

问题描述

我有一个功能可以通过字符串更改特定符号的颜色。它工作正常,除了一个奇怪的问题:

const text = "I was sent, to Earth * to protect [this is inside]"

const container = document.getElementById("container");
container.innerHTML = getColored();

function getColored() {
  let result;
  result = text.replace(/\[/gm, "<span class='box-bracket'>[ </span>");
  result = result.replace(/\]/gm, "<span class='box-bracket'> ]</span>");
  result = result.replace(/\(/gm, "<span class='round-bracket'>( </span>");
  result = result.replace(/\)/gm, "<span class='round-bracket'>) </span>");
  result = result.replace("*", "<span class='separator'>/</span>");
  result = result.replace(/\|([^|]+)\|/g, '<span class="colored">$1</span>');
  // this last one is working wired to reduce the size of string between [] symbols it changes the color!!!
  result = result.replace(/(?<=\[)(.*?)(?=\])/, '<span class="reduced">$1</span>');
  return result;
}
.box-bracket {
  color: #fc0303;
}

.separator {
  color: #fcba03;
}

.colored {
  color: #1e00e3;
}

.round-bracket {
  color: #fc4e03;
}

.reduced {
  font-size: 5px;
}
<div id="container"></div>

我试图在[]没有运气的情况下更改每个符号之间的字符串字体大小......

我使用了这个(函数的最后一行):

result = result.replace(/(?<=\[)(.*?)(?=\])/, '<span class="reduced">$1</span>'); 

但出乎意料的是它只改变了它的颜色(虽然我添加了缩减类!!!)

我怎样才能解决这个问题?我希望能够在[]...之间更改字符串的样式

标签: javascripthtmlcss

解决方案


问题是您的最后一个正则表达式将 this<span class='box-bracket'>[ </span>this is inside<span class='box-bracket'> ]</span>转换为 this <span class='box-bracket'>[<span class="reduced"> </span>this is inside<span class='box-bracket'> </span>]</span>

请注意,您第一次关闭</span>会与最后一个正则表达式的捕获组匹配(.*?),这会导致<span class="reduced">无效,因为它会立即关闭。

解决方案只是将您的“简化”正则表达式放在替换圆括号和方括号的正则表达式之前。

function getColored() {
  let result;
  result = text.replace("*", "<span class='separator'>/</span>");
  result = result.replace(/\|([^|]+)\|/g, '<span class="colored">$1</span>');
  result = result.replace(
    /(?<=\[)(.*?)(?=\])/,
    '<span class="reduced">$1</span>'
  );
  result = result.replace('[', "<span class='box-bracket'>[ </span>");
  result = result.replace(']', "<span class='box-bracket'> ]</span>");
  result = result.replace('(', "<span class='round-bracket'>( </span>");
  result = result.replace(')', "<span class='round-bracket'>) </span>");
  return result;
}

此外,您不需要正则表达式来替换方括号和圆括号,因为您只是匹配字符,因此我删除了它们以提高效率。


推荐阅读