Hey i'm loading an html page using ajax into a string, now i want to find the title of the page and use it.
Now i did manage to get the <title>
using regex but that returns the tag along with the title itself and i wish to extract that from the string or could there be a way to do that in the regex?
This is my code :
var title = result.match(/<title[^>]*>([^<]+)<\/title>/);
Now how do i get the actuall title after this/ instead of this?
Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.
You can find your page's title tag within the <head> section of the page's HTML markup.
The HTML <title> tag is used for indicating the title of the HTML document. The body title is placed between the <head> and the </head> tags.
.match()
returns array of matches, use
var title = result.match(/<title[^>]*>([^<]+)<\/title>/)[1];
to get value in parentheses
load your response html string into a jQuery object like so and retrieve the text
$(response).find("title").text();
A relatively simple plain-JavaScript, and non-regex, approach:
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.
I've, obviously, had to guess at your HTML string and removed the (presumed-present) enclosing <html>
/</html>
tags from around the content. However, even if those tags are in the string it still works: JS Fiddle demo.
And a slightly more functional approach:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With