質問

I'm developing multiple advanced expressions which detects 4 things: Urls, twitter usernames, hashtags and hex-colors. It works well if you put the same thing, for example, 4 different hashtags, urls or colors. But when you put, for example a hashtag and a different thing like a url the hashtag disappears. Here you can see the 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>"
};

You can try out here: http://jsfiddle.net/esa_u7/KrTMW/ Write in the first textarea: "#fff, #000, #00f" without slashes (as you can see it worked) and then add a twitter username like @example. Why are all the hashtag disappears.

役に立ちましたか?

解決 2

I found the error. I was making a loop like:

$.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");
        }
    });
});

And the correct way to do it is:

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++;
});

他のヒント

Hash tags can be used as regex delimiters and need to be escaped \#

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top