[英]Change color of string between two | symbols
How can we change color of string between two |
我们如何在两个|
之间改变字符串的颜色? symbols in the given string:给定字符串中的符号:
Here is the prototype:这是原型:
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>
Edit: It's not that basic you should select both the string with and without |编辑:这不是最基本的,你应该 select 带和不带 | 的字符串symbols because we want only the string not the symbols...符号因为我们只想要字符串而不是符号......
This can be done using String.prototype.replace()这可以使用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>
Or also by using a function:或者也可以使用 function:
string.replace(/\|\b([^|]+)\b\|/g, (fullMatch, group1) => {
return `<span class="colored">${group1}</span>`
});
And here's a Regex101 link to the regular expression from the example above.这是上例中正则表达式的Regex101 链接。
Another example:另一个例子:
Basic regular expression with replace带替换的 基本正则表达式
const string = "Starting |this should be colored| there may be more |colored too|"; const result = string.replace(/\|([^|]+)\|/g, '<span class="colored">$1</span>'); const container = document.getElementById("container"); container.innerHTML = result;
.colored { color: #1e00e3; }
<div id="container"></div>
Note: It works fine with basic text like that is given.注意:它可以很好地处理给出的基本文本。 Add in complexities like HTML markup and this solution would not work.添加诸如 HTML 标记之类的复杂性,此解决方案将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.