4

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

"<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>"

Ideally I would like to capture just the ID value 12120012732dafd4

3 Answers 3

3

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();
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

You can do this with JSDom like this:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;

const htmlString = /*html*/`<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>`

const dom = new JSDOM(htmlString);
const value = dom.window.document.querySelector("input[name='ID']").value 

console.log(value); // "12120012732dafd4"

Demo in RunKit

Further Reading:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.