【问题标题】:Iterate through regex'd results and replace it separately遍历正则表达式的结果并单独替换它
【发布时间】:2013-01-26 16:18:44
【问题描述】:

简短:我正在寻找类似 jQuery 的 .each() 正则表达式函数。

我有一个长文本,其中包含一些<abcd1234> 格式的短字符串。 abcd1234 应包含在 <span> 中,包括为每个找到的字符串生成的文本颜色。我发现这个函数可以这样做:https://stackoverflow.com/a/3426956/237312

function nickFormat(text) {
            var exp = /\&lt\;(.*)\&gt\;/ig;
            name = exp.exec(text);
            return text.replace(exp, "&lt;<span style='color: #"+intToARGB(hashCode(RegExp.$1)).substr(0, 6)+"'>$1</span>&gt;");
        }

这是我当前替换找到的字符串的代码,这意味着正则表达式正在工作。但并不像最初预期的那样。每个找到的字符串都用相同的颜色着色。

有什么办法,怎么解决?

【问题讨论】:

标签: javascript


【解决方案1】:

感谢 Felix Kling,我能够非常快速地解决问题。谢谢!

function nickFormat(text) {
    var exp = /\&lt\;(.*)\&gt\;/ig;

    function makeItSo(match) {
        return "<span style='color: #"+intToARGB(hashCode(match)).substr(0, 6)+"'>"+match+"</span>";
    }
    return text.replace(exp, makeItSo);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多