【问题标题】:Advanced Regular Expressions in JavascriptJavascript 中的高级正则表达式
【发布时间】:2013-08-19 20:03:07
【问题描述】:

我正在开发多个高级表达式,可以检测 4 项内容:网址、推特用户名、主题标签和十六进制颜色。如果您放置相同的内容,例如 4 个不同的主题标签、网址或颜色,效果会很好。但是,当您放置例如主题标签和 url 之类的不同内容时,主题标签就会消失。 在这里你可以看到RegularExp:

var RegularExp = {
    twitter: /(^|[,\s])@(\w{1,15})/g,
    color: /(^|[,\s])#((?:[a-fA-F0-9]){3}|(?:[a-fA-F0-9]){6})/g,
    hashtag: /(^|[,\s])#(\w{1,15})/g,
    url: /(^|\s)(((http(s)?:\/\/|ftp(s)?:\/\/)?([a-zA-Z0-9_-]+\.)?(?:[a-zA-Z0-9]+)(?:\.[a-z]{2,4}){1,2})(\/.*)*)/g
},
Replacer = {
    twitter: "$1<a rel='nofollow' target='_blank' href='http://twitter.com/$2'>@$2</a>",
    color: "$1<span class='hex-color' style='background-color:#$2 !important'>#$2</span>",
    hashtag: "$1<a rel='nofollow' target='_blank' href='http://twitter.com/search?q=%23$2&src=hash'>#$2</a>",
    url: "$1<a rel='nofollow' target='_blank' href='$2'>$2</a>"
};

您可以在这里试用:http://jsfiddle.net/esa_u7/KrTMW/ 在第一个文本区域中写入:“#fff, #000, #00f” 不带斜杠(如您所见),然后添加一个 Twitter 用户名,如 @example。 为什么所有标签都消失了。

【问题讨论】:

  • jsfiddle 似乎对我没有任何作用。它将文本从顶部文本区域复制到另一个文本区域,但没有任何反应。
  • @Pointy 你是对的,原因是 JSFiddle 加载了另一个版本的 Zepto 库;控制台说函数 contents() 不存在,但现在我已经更新了它。现在,您可以再试一次。

标签: javascript regex url hashtag zepto


【解决方案1】:

哈希标签可以作为正则分隔符,需要转义\#

【讨论】:

  • AFAIK,这不是真的。
  • 在 JavaScript 中绝对不是这样。
【解决方案2】:

我发现了错误。我正在制作一个循环,例如:

$.each(RegularExp, function (name, value) {
    if (RegularExp[name].test(self.nodeValue)) {
        $(self).replaceWith(self.nodeValue.replace(RegularExp[name], Replacer[name]));
    }
    $output.find("span").each(function () {
        if ($(this).hasClass("hex-color")) {
            $(this).contrastColor("color", "background-color");
        }
    });
});

而正确的做法是:

var indice = 1,
    texto = this.nodeValue;
$.each(RegularExp, function (name, value) {
    if (RegularExp[name].test(self.nodeValue)) {
        texto = texto.replace(RegularExp[name], Replacer[name])
    }
    if(indice == Object.keys(RegularExp).length){
        $(self).replaceWith(texto);
    }
    $output.find("span").each(function () {
        if ($(this).hasClass("hex-color")) {
            $(this).contrastColor("color", "background-color");
        }
    });
    indice++;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2011-12-21
    • 2015-11-07
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    相关资源
    最近更新 更多