2012-07-03 43 views
0

我的應用程序從instagram中提取圖像,我想知道如何使用JS來遍歷文檔,並簡單地查找每個包含#標籤並追加的項目一個URL。如何將href附加到具有標籤的項目

My instagram photo contains the following tags #instagram #photo #tags 

,結果最終看起來像

我的Instagram照片包含以下標記#instagram#photo#tags

回答

2

試試這個

var x = "My instagram photo contains the following tags #instagram #photo #tags"; 

var split = x.split(" "); 
for(var i=0; i< split.length; i++){ 
    if(split[i].indexOf('#') >= 0){ 
     split[i] = '<a href=\"http://myapp.com/tag/'+split[i].substring(1)+'\">'+split[i]+'</a>'; 
    } 
} 
console.log(split.join(" ")); 

這裏是小提琴 http://jsfiddle.net/9XQBC/

0

ü可以追加一個#到HREF, 試試這個

var tag = '#instagram'; 

$('.myPhoto').attr('href',tag);//this will change current href 
0

找到一種簡單的解決

hashtag_regexp = /#([a-zA-Z0-9]+)/g; 

function linkHashtags(text) { 
    return text.replace(
     hashtag_regexp, 
     '<a class="hashtag" href="https://stackoverflow.com/search?q=$1">#$1</a>' 
    ); 
} 

$(document).ready(function(){ 
    $('.comment').each(function() { 
     $(this).html(linkHashtags($(this).html())); 
    }); 
});​ 
-1

遍歷每個錨鏈路,測試散列標籤的存在,然後更改基於一個「真」狀態的URL。

$.each($('a'), function(i,v){ 
    var findHash = /#/g; 
    var scenario = findHash.test($(v).attr('href')); 
    if(scenario == true){ 
    var grabHref = $(v).attr('href'); 
    var addHref = 'somethingafterthehash'; 
    $(v).attr('href', grabHref + addHref); 
    console.log($(v).attr('href')); 
    } 
}); 

jsFiddle here

+0

沒有錨,OP想要添加這些。 –

+0

@Florian Margaine它在哪裏說的? – Ohgodwhy

相關問題