如何在JavaScript中获取部分URL?

时间:2013-05-31 14:12:48

标签: javascript url

这有什么问题?我只想输出www.google.com

 <script type="text/javascript"> window.onload=function() {  
  var links = document.getElementsByTagName("a");   
   for (var i=0, n=links.length;i<n;i++) {      
     var string = links[i];     
     var str = string;  
     document.write(string);    
     var spl = string.split("/");   
     document.write(spl[2]);       
  } 

  } 

  </script> 

  <a href="http://www.google.com">google</a></br> 

5 个答案:

答案 0 :(得分:1)

您需要获取href值:

window.onload=function() {  
  var links = document.getElementsByTagName("a");   
  for (var i=0, n=links.length;i<n;i++) {      
  var string = links[i].href; //href value
  var str = string;    
  var spl = string.split("/");   
  document.write(spl[2]);       
 } 

答案 1 :(得分:0)

用jquery以这种方式做到:

var ancors = $(document).find('a');
    ancors.each(function(){ 
        var url_parts = $(this).attr('href').split('//');
        alert(url_parts[1]);
});

答案 2 :(得分:0)

var url = links [i] .href.replace(/ ^ https?:\ / \ //,'')

答案 3 :(得分:0)

<script type="text/javascript"> 

  window.onload=function() {  
  var links = document.getElementsByTagName("a");            
var spl = links.split("://");
document.write(spl[1]);    
 } 



 </script> 

 <a href="http://www.google.com">google</a></br>

答案 4 :(得分:0)

var url = "http://www.google.com";
alert(url.split("://")[1]);

工作示例:http://jsfiddle.net/mE3y6/