简体   繁体   中英

JavaScript Hash Tag Parsing Function

I already had two regex functions to parse url's and replies from a json twitter response but I tried to extend it to parse hash tags aswell but I am getting undefined displayed in palce of the hashtag:

// process links, reply and hash tags
tweet = tweet.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function(url) {
        return '<a href="'+url+'">'+url+'</a>';
    }).replace(/B@([_a-z0-9]+)/ig, function(reply) {
        return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    }).replace(/#([a-zA-Z0-9]+)/g), function(hash) {
        return '<a class="hashtag" target="_blank" href="http://twitter.com/#search?q='+$1+'">#'+$1+'</a>';
    };

Any pointers on where I'm going wrong?

最后一个替换中的函数接受一个哈希参数,在你的回报中使用它而不是$ 1

The $1 variable is undefined, replace it with hash.substring(1)

Also, you need to close the last function call after the anonymous function declaration.

tweet = tweet.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function(url) {
    return '<a href="'+url+'">'+url+'</a>';
}).replace(/B@([_a-z0-9]+)/ig, function(reply) {
    return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
}).replace(/#([a-zA-Z0-9]+)/g, function(hash) {
    return '<a class="hashtag" target="_blank" href="http://twitter.com/#search?q='+hash.substring(1)+'">#'+hash.substring(1)+'</a>';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM