Skip to content Skip to sidebar Skip to footer

Parse Html String To Js In Nodejs

I was wondering if there was a better way to capture a value inside an input tag rather than using regex in JS. '

Solution 1:

Since there is no DOM in node you have to initialize a cheerio instance from an HTML string. (this example comes from the cheerio readme)

var cheerio = require('cheerio'),
        $ = cheerio.load("<html><head></head><body onload=\"document.form1.submit()\"><form name=\"form1\" method=\"post\" action=\"\" ><input name=\"Token\" type=\"hidden\" value=\"\"><input name=\"ID\" type=\"hidden\" value=\"12120012732dafd4\"></form></body></html>"
);
    
    $('input').val();

Solution 2:

You can use cheerio:

h = "[your HTML]"const $ = cheerio.load(h)
console.log("Value:", $("form input[name='ID']").attr("value"))

Demo: https://runkit.com/adelriosantiago/get-attr-from-html-in-node

Alternatively you can use jsdom or htmlparser.

Post a Comment for "Parse Html String To Js In Nodejs"