用<为纯文本字符串着色;span>元素

Colorize plain text string with <span> elements

本文关键字:span 元素 gt 文本 lt 字符串      更新时间:2023-09-26

好吧,所以我做了这个函数:

String.prototype.colorize = function() {
    return this.replace(/&([0-9]{1,3})/gi, function($0, $1, offset) {
        return (offset > 0 ? "</span>" : "") + '<span style="color: hsl(' + $1 + ', 100%, 50%)">';
    });
};

它基本上将纯文本字符串转换为带有颜色的html跨度,例如&240Hello使用HSL色阶变为蓝色。

现在的问题是,只有当它找到任何匹配项时,我才需要它在字符串的最后添加</span>,以便关闭它自己。我可以把它存储在str中,然后做if (str.indexOf("span") > -1) str += "</span>"。但我认为这看起来很难看,有没有办法在replacer函数中立即解决这个问题?

我注意到这其实并不重要,因为如果你使用innerHTML附加它,它会自动生成一个</span>标记,为了清楚起见,我该怎么做?

提前谢谢。

所以我找到了解决方案,它甚至比问题的代码更干净:

String.prototype.colorize = function() {
    return this
        .replace(/&([0-9]{1,3})/g, '</span><span style="color: hsl($1, 100%, 50%)">')
        .replace(/(<'/span>)(.*)/g, "$2$1");
};