0

I have html stored in a var

var html = "<div class="RiP" style="text-align: left;"><div class="clr"></div><input name="extraMP" value="999" type="hidden"><div class="txta dropError">Slide to activate</div><div class="bgSlider"><div class="Slider ui-draggable"></div></div><div class="clr"></div><input name="randomValue" value="randomValue2" type="hidden"></div>"

I want to extract "randomValue" and "randomValue2".

Maybe I should use cheerio? I tried with it but I had hard time managing to do it.

Rimmble
  • 1
  • 2
  • 2

2 Answers2

1

If cheerio is hard for you - you could use regular expression to get the values. For easily access you could provide class attribute for the <input> like:

<input class="className" name="randomValue" value="randomValue2" type="hidden">

your regexp will be:

const match = html.match(/<input\s*class="className"\s*name="(.+?)"\s*value="(.+?)"/m)
match[1] // randomValue
match[2] // randomValue2

With cheerio it will be:

const cheerio = require('cheerio');
const html = `<div class="RiP" style="text-align: left;"><div class="clr"></div><input name="extraMP" value="999" type="hidden"><div class="txta dropError">Slide to activate</div><div class="bgSlider"><div class="Slider ui-draggable"></div></div><div class="clr"></div><input class="myClass" name="randomValue" value="randomValue2" type="hidden"></div>`

const $ = cheerio.load(html);

$('.myClass').val(); // randomValue2
$('.myClass').attr('name'); // randomValue
Eugene
  • 156
  • 3
  • [Don't use regex to parse HTML](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – ggorlen Jan 09 '23 at 22:35
0

What you might do using cheerio is to find the last input inside the RiP class and get the name and value attribute:

var html = `<div class="RiP" style="text-align: left;"><div class="clr"></div><input name="extraMP" value="999" type="hidden"><div class="txta dropError">Slide to activate</div><div class="bgSlider"><div class="Slider ui-draggable"></div></div><div class="clr"></div><input name="randomValue" value="randomValue2" type="hidden"></div>`;

const cheerio = require('cheerio');
const $ = cheerio.load(html);

let input = $('.RiP input').last();
console.log(input.attr('name'));
console.log(input.val());

Result:

randomValue
randomValue2

Note that it is not advisable to parse html with regex

The fourth bird
  • 154,723
  • 16
  • 55
  • 70