嘿,我正在使用ajax将一个html页面加载到一个字符串中,现在我想找到页面的标题并使用它。
现在我已经成功使用正则表达式获取了<title>
,但是那返回的是标签以及标题本身,我希望从字符串中提取出来,或者有没有一种方法可以在正则表达式中做到这一点?
这是我的代码:
var title = result.match(/<title[^>]*>([^<]+)<\/title>/);
现在我该如何获取实际标题/而不是这个标题?
嘿,我正在使用ajax将一个html页面加载到一个字符串中,现在我想找到页面的标题并使用它。
现在我已经成功使用正则表达式获取了<title>
,但是那返回的是标签以及标题本身,我希望从字符串中提取出来,或者有没有一种方法可以在正则表达式中做到这一点?
这是我的代码:
var title = result.match(/<title[^>]*>([^<]+)<\/title>/);
.match()
返回匹配到的数组,使用。var title = result.match(/<title[^>]*>([^<]+)<\/title>/)[1];
获取括号中的值
/<title>(.*?)</title>/i
正则表达式。如果您使用jQuery,则可以创建文档片段并从中获取值$(yourHtmlString).find('title').text()
。 - Ivan Solntsev将您的响应HTML字符串加载到jQuery对象中,像这样检索文本
$(response).find("title").text();
var div = document.createElement('div'); div.innerHTML = response; $(div).find('title').text();
。 - Veli Gebrev一个相对简单的纯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);
显然,我必须猜测您的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);
img
标签,现在变得非常容易了!!! - denikov代码:
var title = result.match("<title>(.*?)</title>")[1];
将正则表达式设置为不区分大小写。
以下是完整的代码:
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!");
}
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);
试试这个,我认为这会有帮助。在我的情况下它完美地工作了。:)
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");