2017-01-02 106 views
1

在這裏,我有這樣的http://www.thidiff.com/&sa=U&ved=0ahUKEwiexM7XmaPRAhWmrVQKHUmXDXMQ_BcIYygBMBA&usg=AFQjCNEf9K9tDpISjuX1qkTOHK_aeiPrwQ我怎樣才能獲得網址前面的與

鏈接我想是http://www.thidiff.com/&之前如何是可以做到的

我有樣hrefs

$('a.ganna').each(function(){ 
 
    var href = $(this).attr('href'); 
 
    var ampIndex = href.indexOf('&'); 
 
    console.log(ampIndex); 
 
    var httIndex = href.indexOf('htt'); 
 
    console.log(httIndex); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<a class="ganna" href="/url?q=http://www.thidiff.com/&amp;sa=U&amp;ved=0ahUKEwiexM7XmaPRAhWmrVQKHUmXDXMQ_BcIYygBMBA&amp;usg=AFQjCNEf9K9tDpISjuX1qkTOHK_aeiPrwQ">Website</a> 
 

 

 
<a class="ganna" href="/url?q=http://www.sahasraadvisoryagency.com/&amp;sa=U&amp;ved=0ahUKEwjOxOnmmaPRAhUHh1QKHRR3B4cQ_BcIVCgBMA4&amp;usg=AFQjCNFIbN_BcKr1501xZcqpER22-Bfy4A">Website</a>

我的預期輸出

http://www.thidiff.com/ 

http://www.sahasraadvisoryagency.com/ 
+0

@baao,請確認這個'與'答案是非常不同的question'問題是關係匹配字符串的切割' – EaB

回答

2

您looing爲substr功能:

href.substr(httIndex, ampIndex-httIndex); 

工作示例可以在這裏找到:

https://jsfiddle.net/04fzt0br/

編輯: 簽名的功能是: string.substr(startIndex, length)

+0

非常感謝我不知道'substr()'wo因此,我發佈了它,非常感謝 – EaB

+0

這裏'-'標誌是什麼表示'ampIndex-httIndex'是它的'減號'? – EaB

+0

是的,它是一個負號。 –

1

你也可以這樣做。

$('a.ganna').each(function(){ 
 
    var href = $(this).attr('href').split('=')[1]; //splitting by `=` sign and getting 2nd element 
 
    var domain = href.slice(0, href.indexOf('&')); //slicing string upto `&` 
 
    console.log(domain); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<a class="ganna" href="/url?q=http://www.thidiff.com/&amp;sa=U&amp;ved=0ahUKEwiexM7XmaPRAhWmrVQKHUmXDXMQ_BcIYygBMBA&amp;usg=AFQjCNEf9K9tDpISjuX1qkTOHK_aeiPrwQ">Website</a> 
 

 

 
<a class="ganna" href="/url?q=http://www.sahasraadvisoryagency.com/&amp;sa=U&amp;ved=0ahUKEwjOxOnmmaPRAhUHh1QKHRR3B4cQ_BcIVCgBMA4&amp;usg=AFQjCNFIbN_BcKr1501xZcqpER22-Bfy4A">Website</a>

1

使用正則表達式來提取網址:

var re = /http:\/\/+(www.[a-z0-9]+).com/g; 
 
var sel = document.querySelectorAll('.ganna'); 
 

 
[].forEach.call(sel, function(el){ 
 
    console.log(JSON.stringify(el.href.match(re)[0], 0, 0)); 
 
})
<a class="ganna" href="/url?q=http://www.thidiff.com/&amp;sa=U&amp;ved=0ahUKEwiexM7XmaPRAhWmrVQKHUmXDXMQ_BcIYygBMBA&amp;usg=AFQjCNEf9K9tDpISjuX1qkTOHK_aeiPrwQ">Website</a> 
 
<a class="ganna" href="/url?q=http://www.sahasraadvisoryagency.com/&amp;sa=U&amp;ved=0ahUKEwjOxOnmmaPRAhUHh1QKHRR3B4cQ_BcIVCgBMA4&amp;usg=AFQjCNFIbN_BcKr1501xZcqpER22-Bfy4A">Website</a>

相關問題