2012-11-19 82 views
5

嘿,我正在加載一個html頁面使用ajax成一個字符串,現在我想找到頁面的標題和使用它。如何獲得一個html字符串中的標題標籤?

現在我設法使用正則表達式得到<title>,但它返回的標籤與標題本身,我希望從字符串中提取該標記或可以有一種方法來在正則表達式中做到這一點?

這是我的代碼:

var title = result.match(/<title[^>]*>([^<]+)<\/title>/); 

現在我該怎樣拿到實際工作頭銜在此之後/,而不是這個?

+0

使用jquery挑選標題標籤...不要使用正則表達式。 – nhahtdh

+0

它在字符串裏面,而不在文檔中 –

+1

我意識到這一點,但我看到了解析HTML字符串並對其進行操作的解決方案。編輯:找到http://stackoverflow.com/questions/704679/parse-html-string-with-jquery – nhahtdh

回答

9

您迴應HTML字符串加載到一個jQuery對象,像這樣和檢索文字

$(response).find("title").text(); 
+0

該文檔是對ajax請求的響應。因此它可能無法通過document.title – devsathish

+0

訪問好點。我從我的答案中刪除了這個。 – Bruno

+1

由於某種原因(jQuery 1.9.1),這對我沒有直接的幫助,我不得不將這個響應放在一個div中,而是將其加載到一個jQuery對象中。 div.innerHTML = response; $(div).find('title')。text();' –

9

.match()匹配的回報陣列,使用

var title = result.match(/<title[^>]*>([^<]+)<\/title>/)[1]; 

在括號中獲取價值

+0

謝謝ivan,這確實奏效。但是有沒有更好的方法來獲得標題標籤? –

+0

如果你使用html作爲字符串,你可以使用'/ (。*?)/i' regexp。如果您使用jQuery,您可以創建文檔片段並從中選擇值$(yourHtmlString).find('title')。text()' –

2

CODE:

var title = result.match("<title>(.*?)</title>")[1]; 
0

使reg exp不區分大小寫。 下面是完整的代碼:

var regex = /<title>(.*?)<\/title>/gi; 
var input = "<html><head><title>Hello World</title></head>...</html>"; 
if(regex.test(input)) { 
    var matches = input.match(regex); 
    for(var match in matches) { 
    alert(matches[match]); 
    } 
} else { 
    alert("No matches found!"); 
} 
2

一個相對簡單的純JavaScript和非正則表達式,方法:

var htmlString = '<head><title>Some title</title></head><body><p>Some text, in a paragraph!</p></body>', 
    html = document.createElement('html'), 
    frag = document.createDocumentFragment(); 
html.innerHTML = htmlString; 
frag.appendChild(html); 

var titleText = frag.firstChild.getElementsByTagName('title')[0].textContent || frag.firstChild.getElementsByTagName('title')[0].innerText; 

console.log(titleText);​ 

JS Fiddle demo

我明顯不得不猜測您的HTML字符串,並刪除了圍繞內容的(假設存在的)標籤,其中包含<html>/</html>標籤。但是,即使這些標籤在字符串中仍然有效:JS Fiddle demo

與稍微更注重功能的做法:

function textFromHTMLString(html, target) { 
    if (!html || !target) { 
     return false; 
    } 
    else { 
     var fragment = document.createDocumentFragment(), 
      container = document.createElement('div'); 
     container.innerHTML = html; 
     fragment.appendChild(container); 
     var targets = fragment.firstChild.getElementsByTagName(target), 
      result = []; 

     for (var i = 0, len = targets.length; i<len; i++) { 
      result.push(targets[i].textContent || targets[i].innerText); 
     } 
     return result;   
    } 
} 

var htmlString = '<html><head><title>Some title</title></head><body><p>Some text, in a paragraph!</p></body></html>'; 

var titleText = textFromHTMLString(htmlString, 'title'); 

console.log(titleText);​ 

JS Fiddle demo

+0

令人驚歎的答案,沒有正則表達式!我一直在用子串和長度來試圖從html字符串中提取第一,第二,第三個'img'標籤。現在這很容易! – denikov

相關問題