js字符串转DOM,DOM转字符串伪代码

2021-02-04107次阅读原生JsDOM

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

上一篇: 检测是否是icon、png图片的icojs库  下一篇: nrm安装完成运行报错  

js字符串转DOM,DOM转字符串伪代码相关文章