Colorize plain text string with <span> elements
Alright, so I made this function:
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%)">';
});
};
It basically turns a plain text string into html spans with colors so that, for example &240Hello becomes blue, using the HSL color scale.
Now the problem is, I need it to add </span>
in the very end of the string only if it has found any matches so that it closes itself. I could store it in str and then do if (str.indexOf("span") > -1) str += "</span>"
. But I think that looks pretty ugly, is there anyway to fix this right away inside the replacer function?
I have noticed that this doesn't really matter since if you append this using innerHTML it will automagically generate a </span>
tag, well just for clarity, how do I do this?
Thank you in advance.
所以我找到了解决方案,它比问题的代码更清晰:
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");
};
链接地址: http://www.djcxy.com/p/15360.html
上一篇: 电晕,Phonegap,钛之间的比较
下一篇: 使用<span>元素着色纯文本字符串