0

How can I use regex to parse the numeric value (104) assigned to qtyAvail in the below javascript?

<script>
var buyID       = "302";
var qtyAvail    = "104";
var outBehavior = "Default";
if (qtyAvail == "0") {
    if (outBehavior.indexOf("Disallow") != -1) {
        do this
    } else if (outBehavior.indexOf("Allow") != -1) {
        do that
    }
}
</script>
4
  • 4
    I couldn't understand your question, can you please make it more clear ? Commented May 4, 2015 at 1:20
  • 1
    Why do you need a regex for this code? It's already stored in its own variable? If you want numeric value just get rid of the quotes Commented May 4, 2015 at 1:29
  • @Geohut As I added below, this is actually stored as a string in a php variable, and so I am trying to parse the string to save the qtyAvail value as it's own php variable. Regex seems to be the best way to do that with php. Commented May 4, 2015 at 1:40
  • 1
    Preg_match_all('/var\s+qtyAvail\s+=\s+\"(\d+)\";/', $html, $matches); pull out of matches at $matches[1] then intval() it Commented May 4, 2015 at 1:49

1 Answer 1

2

You don't need to use a regular expression, you can just use the native parseInt javascript function:

parseInt(qtyAvail, 10); // the 2nd argument 10 means use base 10 (decimal, as opposed to hexadecimal or something else)
=> 104
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Patrick. I'm actually trying to parse this from scraped data which is stored as a string in a php variable. So I'm looking to search through it with php to pull out just that number and store it as it's own php variable. Is there a php function that can do this without using regex?
I thought this was a javascript question? If you have the variable in PHP as a string and want it to be accessible to javascript, you should just be able to do: var qtyAvial = <?= intval($phpStringVar); ?>

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.