js字符串转DOM,DOM转字符串伪代码。
DOMParser 可以将存储在字符串中的 XML 或 HTML 源代码解析为一个 DOM Document。
const CHARTSET_RE = /(?:charset|encoding)\s{0,10}=\s{0,10}['"]? {0,10}([\w-]{1,100})/i;
function charset(headers: Headers, html: string) {
let matches: any = null;
// 先从header里面取
const contentType =
headers.get('content-type') ?? headers.get('Content-Type');
if (contentType) {
matches = CHARTSET_RE.exec(contentType);
}
// 再从html里面取
if (!matches) {
matches = CHARTSET_RE.exec(html);
}
// 返回结构
let cs = '';
if (matches) {
cs = matches[1].toLowerCase();
if (cs === 'utf-8') {
cs = 'utf8';
}
}
return cs;
}
const getTitleIcon = async(url)=>{
let response;
try {
response = await fetch(url);
} catch (error) {
return '';
}
if (!response.ok) return '';
const buffer = await response.arrayBuffer();
const utf8Decoder = new TextDecoder();
const html = utf8Decoder.decode(buffer);
const cs = charset(response.headers, html);
const decoder = new TextDecoder(cs);
const content = decoder.decode(buffer);
const parser = new DOMParser()
const doc = parser.parseFromString(content, 'text/html');
let title = doc.title;
const link:any = doc.querySelector('link[rel~=shortcut]');
let icon = link? link.href:'';
return [title,icon];
}
DOM转字符串是element.outerHTML。