Return Html filed as plain text

eyal abu hamad
Mega Sage

I'm creating scripted rest api and I want to return a filed that is HTML in plain text

(function process(request, response) {
    var searchText = request.body.data.text;

    if (!searchText) {
        response.setStatus(400);
        response.setBody({ error: "Missing 'text' parameter" });
        return;
    }

    var result = [];
    var gr = new GlideRecord('kb_knowledge');
    gr.addEncodedQuery('textLIKE' + searchText + '^workflow_state=published');
    gr.query();

    while (gr.next()) {
        var htmlText = gr.getValue('text') || '';

        // ✅ Strip HTML tags safely using regex
        var plainText = htmlText.replace(/<[^>]*>/g, '');

        result.push({
            title: gr.getValue('short_description'),
            article_body: plainText.trim()
        });
    }

    response.setStatus(200);
    response.setBody(result);

})(request, response);

still no luck

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@eyal abu hamad 

try to strip the tags

use this

(function process(request, response) {
    var searchText = request.body.data.text;

    if (!searchText) {
        response.setStatus(400);
        response.setBody({
            error: "Missing 'text' parameter"
        });
        return;
    }

    var result = [];
    var gr = new GlideRecord('kb_knowledge');
    gr.addEncodedQuery('textLIKE' + searchText + '^workflow_state=published');
    gr.query();

    while (gr.next()) {
        var htmlText = gr.getValue('text') || '';

        // ✅ Strip HTML tags safely using regex

        var tmp = new GlideElement();
        tmp.setDisplayValue(htmlText);
        var plainText = tmp.getDisplayValue().replace(/<[^>]*>/g, '');

        result.push({
            title: gr.getValue('short_description'),
            article_body: plainText
        });
    }

    response.setStatus(200);
    response.setBody(result);

})(request, response);

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

5 REPLIES 5

@eyal abu hamad 

Hope you are doing good.

Did my reply answer your question?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader