javascript - 在两个之间更改字符串的颜色 | 符号
问题描述
我们如何改变|
给定字符串中两个符号之间的字符串颜色:
这是原型:
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>
编辑:这不是基本的,你应该选择带和不带 | 的字符串。符号,因为我们只想要字符串而不是符号......
解决方案
这可以使用 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 链接。
另一个例子:
推荐阅读
- typescript - 如何调用 Asp.net web Api 登录和令牌认证
- spring-boot-actuator - Spring Boot 管理控制台客户端
- react-native - 世博会错误安装或运行应用程序
- html - 无法“整理”html 文件
- angular - ng test angular 5 不是已知元素
- python - Selenium(使用 python):如何将任何文本输入到 wiki textarea
- python - 使用 python pandas 我想在非空值上规范化数据框列
- java - 添加定义单词的功能
- javascript - 点击 TouchableHighlight 上的焦点文本输入
- scheduling - 无限循环任务的优先级抢占式调度