沐鳴平台註冊登錄_JSON和HTML之間互轉實現

主要實現功能html轉json,再由json恢復html

可去除 style 和 script 標籤

將行內樣式轉換為 js object

將 class 轉換為數組形式

主要依賴於 htmlparser2 ; 這是一個性能優越、功能強大的 html 解析庫

直接上代碼

import { Parser } from "htmlparser2"

const numberValueRegexp = /^\d+$/
const zeroValueRegexp = /^0[^0\s].*$/
const scriptRegexp = /^script$/i
const styleRegexp = /^style$/i
const selfCloseTagRegexp = /^(meta|base|br|img|input|col|frame|link|area|param|embed|keygen|source)$/i

const TAG = 'tag'
const TEXT = 'text'
const COMMENT = 'comment'

/**
 * 去除前後空格
 */
export const trim = val => {
    return (val || '').replace(/^\s+/, '').replace(/\s+$/, '')
}
/**
 * 首字母大寫
 */
export const capitalize = word => {
    return (word || '').replace(/( |^)[a-z]/, c => c.toUpperCase())
}
/**
 * 駝峰命名法/小駝峰命名法, 首字母小寫
 */
export const camelCase = key => {
    return (key || '').split(/[_-]/).map((item, i) => i === 0 ? item : capitalize(item)).join('')
}
/**
 * 大駝峰命名法,首字母大寫
 */
export const pascalCase = key => {
    return (key || '').split(/[_-]/).map(capitalize).join('')
}
export const isPlainObject = obj => {
    return Object.prototype.toString.call(obj) === '[object Object]'
}
/**
 * 行內樣式轉Object
 */
export const style2Object = (style) => {
    if (!style || typeof style !== 'string') {
        return {}
    }
    const styleObject = {}
    const styles = style.split(/;/)
    styles.forEach(item => {
        const [prop, value] = item.split(/:/)
        if (prop && value && trim(value)) {
            const val = trim(value)
            styleObject[camelCase(trim(prop))] = zeroValueRegexp.test(val) ? 0 : numberValueRegexp.test(val) ? Number(val) : val
        }
    })
    return styleObject
}

export const tojsON = (html, options) => {
    options = Object.assign({ skipStyle: false, skipScript: false, pureClass: false, pureComment: false }, options)
    const json = []
    let levelNodes = []
    const parser = new Parser({
        onopentag: (name, { style, class: classNames, ...attrs } = {}) => {
            let node = {}
            if ((scriptRegexp.test(name) && options.skipScript === true) ||
                (styleRegexp.test(name) && options.skipStyle === true)) {
                node = false
            } else {
                if (options.pureClass === true) {
                    classNames = ''
                }
                node = {
                    type: TAG,
                    tagName: name,
                    style: style2Object(style),
                    inlineStyle: style || '',
                    attrs: { ...attrs },
                    classNames: classNames || '',
                    classList: options.pureClass ? [] : (classNames || '').split(/\s+/).map(trim).filter(Boolean),
                    children: []

                }
            }
            if (levelNodes[0]) {
                if (node !== false) {
                    const parent = levelNodes[0]
                    parent.children.push(node)
                }
                levelNodes.unshift(node)
            } else {
                if (node !== false) {
                    json.push(node)
                }
                levelNodes.push(node)
            }
        },
        ontext(text) {
            const parent = levelNodes[0]
            if (parent === false) {
                return
            }
            const node = {
                type: TEXT,
                content: text
            }
            if (!parent) {
                json.push(node)
            } else {
                if (!parent.children) {
                    parent.children = []
                }
                parent.children.push(node)
            }
        },
        oncomment(comments) {
            if (options.pureComment) {
                return
            }
            const parent = levelNodes[0]
            if (parent === false) {
                return
            }
            const node = {
                type: COMMENT,
                content: comments
            }
            if (!parent) {
                json.push(node)
            } else {
                if (!parent.children) {
                    parent.children = []
                }
                parent.children.push(node)
            }
        },
        onclosetag() {
            levelNodes.shift()
        },
        onend() {
            levelNodes = null
        }
    })
    parser.done(html)
    return json
}
const setAttrs = (attrs, results) => {
    Object.keys(attrs || {}).forEach(k => {
        if (!attrs[k]) {
            results.push(k)
        } else {
            results.push(' ', k, '=', '"', attrs[k], '"')
        }
    })
}
const toElement = (elementInfo, results) => {

    switch (elementInfo.type) {
        case TAG:
            const tagName = elementInfo.tagName
            results.push('<', tagName)
            if (elementInfo.inlineStyle) {
                results.push(', elementInfo.inlineStyle, '"')
            }
            if (elementInfo.classNames) {
                results.push(', elementInfo.classNames, '"')
            }
            setAttrs(elementInfo.attrs, results)
            if (selfCloseTagRegexp.test(tagName)) {
                results.push(' />')
            } else {
                results.push('>')
                if (Array.isArray(elementInfo.children)) {
                    elementInfo.children.forEach(item => toElement(item, results))
                }
                results.push('</', tagName, '>')
            }
            break;
        case TEXT:
            results.push(elementInfo.content)
            break;
        case COMMENT:
            results.push("<!-- ", elementInfo.content, " -->")
            break;
        default:
        // ignore
    }
}
export const tohtml = json => {
    json = json || []
    if (isPlainObject(json)) {
        json = [json]
    }
    const results = []
    json.forEach(item => toElement(item, results))
    return results.join('')
}


示例

const source = '<div>測試1</div> <div>測試2</div>'
const htmljson = toJSON(source, { skipScript: true, skipStyle: true, pureClass: true, pureComment: true })
const jsonhtml = toHTML(htmljson)
console.log(htmljson)
console.log(jsonhtml)


參數說明

skipScript 過濾 script 標籤,默認 false

skipStyle 過濾 style 標籤,默認 false

pureClass 去掉 class 屬性,默認 false

pureComment 去掉註釋,默認 false

備註

htmlparser2 通過 npm i htmlparser2 –save 進行安裝即可  

原文鏈接 IT浪子の博客 > JSON和HTML之間互轉實現

站長推薦

1.雲服務推薦: 國內主流雲服務商,各類雲產品的最新活動,優惠券領取。地址:阿里雲騰訊雲華為雲

2.廣告聯盟: 整理了目前主流的廣告聯盟平台,如果你有流量,可以作為參考選擇適合你的平台點擊進入

鏈接: http://www.fly63.com/article/detial/9055