2015-07-21 30 views
14

在我的角應用程序使用所見即所得之一我可以插入鏈接沒有協議。這很不好:javascript:閱讀純html字符串和使用DOMparser更改鏈接路徑

我需要解析字符串和更改所有鏈接的

,我嘗試這樣做(如果大公沒有協議http://..):

var content = '<p>7</p><p>77</p><p><br></p><p><a href="http://example.com" rel="nofollow">http://example.com</a></p><p><br></p><p><a href="example.com" target="_blank">example.com</a></p><p><br></p><p><a href="ftp://localhost">ftp://localhost</a></p><p><br></p><p><a href="localhost">localhost</a><br></p>'; 

var addProtocolToLinks = function(URL){ 
    var protocols = ['http', 'https', 'ftp', 'sftp', 'ssh', 'smtp']; 
    var withProtocol = false; 
    if (URL.length > 0){ 
     protocols.forEach(function(el) { 
     if (URL.slice(0,4).indexOf(el) > -1){ 
      withProtocol = true; 
     } 
     }); 
     var newURL = URL; 
     if (!withProtocol){ 
     newURL = 'http://' + URL; 
     } 
     console.log(newURL + ' ' + URL); 
     return newURL; 
    } 
}; 

var parser = new DOMParser(); 
var doc = parser.parseFromString(content, "text/html"); 
var links = doc.getElementsByTagName("a"); 
for(var i=0; i<links.length; i++) { 
    links[i].setAttribute('href', addProtocolToLinks(links[i].href)); 
    console.log('result: ' + links[i].getAttribute('href')); 
} 

console.log('result html: '); 
console.log(doc); // also i need to fetch only my var content part, without html, body etc 

http://jsfiddle.net/r3dgeo23/

但由於某些原因,它無法正常工作。我做錯了什麼?

回答

3

如果我完全瞭解你的問題,這應該工作...

function jsF_addHTTP(url) 
    { 

     if (url !== "") 
     { 
      // Insert HTTP if it doesn't exist. 

      if (!url.match("^(http|https|ftp|sftp|ssh|smtp)://")) 
      { 
       url = "http://" + url; 
      } 
     } 
     return url; 
    } 
4

你幾乎一切權利,除了:

link[i].href 

的回報,如果沒有協議集不確定。因此,你給了函數addProtocolToLinks(undefined),它不起作用。

您可以使用:

getAttribute('href'); 

,使其工作,看到這個小提琴: http://jsfiddle.net/r3dgeo23/3/

/////編輯

這裏是只取了一個小提琴內容部分而不是整個html: http://jsfiddle.net/r3dgeo23/5/

///// EDIT2

創建函數中使用的唯一ID的容器:

var container = document.createElement('div'); 
container.setAttribute("id", "content"); 
container.innerHTML = content; 

http://jsfiddle.net/r3dgeo23/6/

+0

))確保大公我的內容是動態的,我不僅可以將其更改爲''

)...取不這樣做) – brabertaser19

+0

那麼你可以創建你的函數內的容器 - 我編輯我的答案。 –

1

試試這個.. 據WORKING

var addProtocolToLinks = function(URL){ 
protocols = ['http', 'https', 'ftp', 'sftp', 'ssh', 'smtp']; 
protocols.forEach(function(item) { 
    if(url.indexOf(item) != -1) { 
    newUrl = "http://"+url.substr(url.indexOf("//")+2); 
    }  
}); 
return newUrl; 
} 

示例演示在這裏http://jsfiddle.net/d9p9534h/

讓我知道它是否有效

1

這個怎麼樣?

function ensureProtocol(href) { 
    var match = href.match(/^((\w+)\:)?(.*)/); 
    var protocol = match[1] || 'https:'; 
    return protocol + match[3]; 
} 

注:並非所有的URI有一個授權部分。這就是爲什麼正則表達式不包括//。見this article

1
function Protocol(url) 
    { 

     if (url !== "") 
     { 


      if (!url.match("^(http|https|ftp|sftp|ssh|smtp)://")) 
      { 
       url = "http://" + url; 
      } 
     } 
     return url; 
    }