Search code examples
javascriptstringvariablesintegeruserscripts

JS: how to find a specific string, then extract an integer?


I'm trying to write a userscript for a game I'm playing. It uses this piece of HTML code:

    <td valign="center">
      <b>ten-leaf clover</b>
       (4 left in stock for today)
    </td>

This is a picture of what we're talking about:

enter image description here

The script should search for a string containing the words "left in stock for today", then look for an integer within this string. (The '4' is not constant, it changes every day.) Lastly, I would like to store this integer as a variable, so I can replace the '1' in the input field. Like this:

    var clover = EnterCodeHere
    $("input.text[name='quantity']").val(clover);

Solution

  • You can used a regex like so:

    var textToSearch = $("td").innerHtml(); //You'll need a better selector than this. better to use a class or id
    var clover = parseInt(textToSearch.match(/\d+\s*left in stock for today/)[0].match(/\d+/)[0]);
    $("input.text[name='quantity']").val(clover);
    

    You may want to check the array isn't empty before just taking the first value but if your confident it'll be there should be grand.