1

here i have links like this http://www.thidiff.com/&sa=U&ved=0ahUKEwiexM7XmaPRAhWmrVQKHUmXDXMQ_BcIYygBMBA&usg=AFQjCNEf9K9tDpISjuX1qkTOHK_aeiPrwQ

what i want is http://www.thidiff.com/ which before & how it can be done

i have sample 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>

my expected output :

http://www.thidiff.com/

http://www.sahasraadvisoryagency.com/
  • @baao, please verify this `question` with that answer `it is very different question it is related cutting of matching string` –  Jan 02 '17 at 11:46

3 Answers3

1

You are looing for the substr function:

href.substr(httIndex, ampIndex-httIndex);

Working example available here:

https://jsfiddle.net/04fzt0br/

EDIT: Signature of the function is : string.substr(startIndex, length)

Didier Aupest
  • 3,227
  • 2
  • 23
  • 35
0

You can also do like this.

$('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>
Jyothi Babu Araja
  • 10,076
  • 3
  • 31
  • 38
0

Use a regex to extract a url:

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>
Jai
  • 74,255
  • 12
  • 74
  • 103