javascript - 更改 [ ] 符号之间的样式的问题
问题描述
我有一个功能可以通过字符串更改特定符号的颜色。它工作正常,除了一个奇怪的问题:
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>');
但出乎意料的是它只改变了它的颜色(虽然我添加了缩减类!!!)
我怎样才能解决这个问题?我希望能够在[]
...之间更改字符串的样式
解决方案
问题是您的最后一个正则表达式将 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;
}
此外,您不需要正则表达式来替换方括号和圆括号,因为您只是匹配字符,因此我删除了它们以提高效率。
推荐阅读
- amazon-web-services - S3 存储桶访问被拒绝,即使是管理员
- angular - 尝试使用视频课程学习 Angular - 卡在 ViewContainerRef 和 TemplateRef
- gradle - 我需要通过 gradle 调用 Cucumber Runner,然后它也会执行所有测试执行和报告
- android - 如何在 Flutter 应用中创建启动屏幕
- html - scss 中有 eval() 函数吗?
- javascript - 密钥发送操作中西里尔字母的键码/编码问题
- c# - Regex表达式中如何区分十六进制数和十进制数?
- python - 根据两个日期过滤数据框中的值
- c++ - 如何在 C++ 中循环遍历具有不同长度的动态二维数组
- reactjs - 使用 create-react-app 创建自定义绝对路径