如何从HTML字符串中获取标题标签?

9

嘿,我正在使用ajax将一个html页面加载到一个字符串中,现在我想找到页面的标题并使用它。

现在我已经成功使用正则表达式获取了<title>,但是那返回的是标签以及标题本身,我希望从字符串中提取出来,或者有没有一种方法可以在正则表达式中做到这一点?

这是我的代码:

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

现在我该如何获取实际标题/而不是这个标题?

使用jQuery选择标题标签...不要使用正则表达式。 - nhahtdh
它在字符串中而不在文档中。 - eric.itzhak
1
我知道这一点,但是我见过解决方案可以解析HTML字符串并对其进行操作。编辑:找到https://dev59.com/MHRB5IYBdhLWcg3wJkhC - nhahtdh
如果你能给我提供一些解决方案的链接,我会非常高兴的,因为这样可以节省很多时间。 - eric.itzhak
@nhahtdh 如果你将其提交为答案,我会投票赞成,并且提交者应该接受它。毫无疑问,这是最干净的方式。 - tucuxi
@tucuxi:这个问题已经有答案了。 - nhahtdh
7个回答

18
.match() 返回匹配到的数组,使用。
var title = result.match(/<title[^>]*>([^<]+)<\/title>/)[1];

获取括号中的值


谢谢Ivan,这个方法确实可行。不过有没有更好的方法来获取标题标签? - eric.itzhak
1
如果您正在使用HTML字符串,可以使用/<title>(.*?)</title>/i正则表达式。如果您使用jQuery,则可以创建文档片段并从中获取值$(yourHtmlString).find('title').text() - Ivan Solntsev

13

将您的响应HTML字符串加载到jQuery对象中,像这样检索文本

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

该文档是对ajax请求的响应。因此,可能无法通过document.title访问。 - devsathish
4
由于某种原因(jQuery 1.9.1),这对我来说没有直接起作用,所以我不得不将响应放入一个 div 中,并将其加载到 jQuery 对象中: var div = document.createElement('div'); div.innerHTML = response; $(div).find('title').text(); - Veli Gebrev

4

一个相对简单的纯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演示

显然,我必须猜测您的HTML字符串并从内容中删除(假定存在的)<html>/</html>标记。但是,即使这些标记在字符串中仍然有效:JS Fiddle演示

而且还有一个稍微更具功能性的方法:

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.


太棒了,没有正则表达式!!!我一直在用子字符串和长度来提取HTML字符串中的第一个、第二个、第三个img标签,现在变得非常容易了!!! - denikov

3

代码:

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

0

将正则表达式设置为不区分大小写。

以下是完整的代码:

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!");
}

0
正则表达式不是在 HTML 中查找内容的好方法,因为 HTML 太复杂了,一个简单的正则表达式无法胜任。(请参见有关此主题的著名帖子。)相反,使用 {{link2:DOMParser}} 的 {{link3:parseFromString}} 方法,然后在生成的文档中查找:

const html = "<!doctype html><head><title>example</title>";

const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const title = doc.querySelector("title");
console.log(title.textContent);


0

试试这个,我认为这会有帮助。在我的情况下它完美地工作了。:)

 var FindTag=(data='',tag='')=>{
    var div=document.createElement('div');
    div.innerHTML=data;
    data=$(div).find(tag)[0].outerHTML;
    return data;
 }

var data=FindTag(data,"title");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接