2013-07-24 144 views
-2

如何替換所有鏈接的URL如果找到sites.com on the href? 例如:使用jquery替換網頁中的所有鏈接(href)

Original Link --->New Link

從這個HREF鏈接

http://one.sites.com/1234/12/page.html 
http://two.sites.com/img/dir/index.html 
http://any.sites.com/any/any/any.html 
http://*.sites.com/*/*/*.* 

http://one.sites.com/ 
http://two.sites.com/ 
http://any.sites.com/ 
http://*.sites.com/ 

我試過使用jquery:

$("a[href*='http://one.sites.com/']").attr('href','http://one.sites.com') 

但它只會取代一個鏈接。

我認爲,如果將其與正則表達式,它會自動替換每個HREF

var isUrl=/(\()((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\))|(\[)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\])|(\{)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\})|(<|&(?:lt|#60|#x3c);)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(>|&(?:gt|#62|#x3e);)|((?:^|[^=\s'"\]])\s*['"]?|[^=\s]\s+)(\b(?:ht|f)tps?:\/\/[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]+(?:(?!&(?:gt|#0*62|#x0*3e);|&(?:amp|apos|quot|#0*3[49]|#x0*2[27]);[.!&',:?;]?(?:[^a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]|$))&[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]*)*[a-z0-9\-_~$()*+=\/#[\]@%])/img; 

正則表達式代碼的網頁有sites.com上的所有鏈接上面檢查成功鏈接一樣的表達:

http://one.sites.com/1/2/page.html 

如何使用jQuery實現它?請幫助

+1

你有你自己嘗試新鮮事物? – putvande

+0

你想在旅途中做到這一點嗎?或者你解析一個靜態文件? – amaurs

+0

@putvande我試過使用jquery。我不知道如何使用jQuery的正則表達式 – Vimux

回答

1

試試這個代碼:

$('a[href*="sites.com"]').each(function(){ 
    this.href = this.href.replace(/(.*?sites.com\/)/, function(str, p1){ 
     return p1 
    }) 
}) 

或者沒有正則表達式

$('a[href*="sites.com"]').each(function(){ 
    var index = this.href.indexOf(".com/"); 
    this.href = this.href.slice(0, index+5) 
}) 
+0

謝謝,它的工作原理沒有regExp ..對不起,如果我不能給+1 .. – Vimux

-1

試試這個:

$('a[href*="sites.com"]').each(
function(){ 
    // Do a substring here to keep the beginning of the path (domain) 
    $(this).attr("href", "http://any.sites.com/"); 
}) 
+0

-1從鏈接中獲取幫助...我可以知道原因嗎? – glautrou

+0

正則表達式難以編寫/維護,在你的情況我認爲你應該避免這種情況,使用substr()和indexOf(),而不是 – glautrou