如果在href上找到 sites.com ,如何替换所有链接的网址? 例如:
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上有sites.com的任何页面上的所有链接
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;
上面的正则表达式代码成功检查了链接的表达式:
http://one.sites.com/1/2/page.html
如何使用jquery实现它?请帮忙
答案 0 :(得分:1)
试试这段代码:
$('a[href*="sites.com"]').each(function(){
this.href = this.href.replace(/(.*?sites.com\/)/, function(str, p1){
return p1
})
})
或没有regExp
$('a[href*="sites.com"]').each(function(){
var index = this.href.indexOf(".com/");
this.href = this.href.slice(0, index+5)
})
答案 1 :(得分:-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/");
})