rbren / rss-parser

A lightweight RSS parser, for Node and the browser
MIT License
1.38k stars 209 forks source link

Convert item.title with html tags to html #232

Open dogia opened 2 years ago

dogia commented 2 years ago

I have desingned if helps a function that convert an item with html subtags to html

use: extract(item.title);

function extract(item, tag = '') {
    if(typeof item === 'object') {
        if(Array.isArray(item)) {
            let content = '';
            for(const i in item) {
                content = `${content} ${extract(item[i], tag)}`;
            }
            while(content[0] === ' ')
                content = content.substring(1);
            return content;
        } else {
            let attr = '';
            let content = '';
            for(const i in item) {
                if(i === '$') {
                    for(const j in item[i]) {
                        const value = item[i][j];
                        attr = `${attr} ${j}="${value}"`;
                    };
                } else if(i === '_') {
                    content = `${content} ${item[i]}`;
                } else {
                    content = `${content} ${extract(item[i], i)}`;
                }
            }
            while(content[0] === ' ')
                content = content.substring(1);

            if(tag !== '')
                return `<${tag}${attr}>${content}</${tag}>`;
            else
                return content;
        }
    } else if(typeof item === 'string') {
        if (tag !== '')
            return `<${tag}>${item}</${tag}>`;
        else
            return `${item}`;
    }
}