in postman how to to get specific thing from html response

Viewed 162

So the html I get looks like this:

<!DOCTYPE html>
<html>
<head>
--------------------
</head>
<body>
    <script>
        function onClickButton(word) {
        if (word == 'yes'){
          var authorizationCode = '360ad5ce-ecfe-4ad4-83d1-9254e89a3ccc';
          var state = 'c8271b81-4229-6a1f-bf9c-758f11c1f5b1';
        } else {
          alert(word);
        }
      }
    </script>
    <div class="shb-psua-sign-app-sandbox-container">
    --------------------
    </div>
</body>
</html>

How do I get var authorizationCode value? and save it as a variable in postman.
My code for now looks like this

const $ = cheerio.load(pm.response.text())
var script = $("script").text();

pm.collectionVariables.set("access_token", script);

Now I get the whole script but how do I just get the value of the authorizationCode or even just using the gotten variable to get the value out of it?

2 Answers

You can use a Regular Expression to get the value of the authorizationCode variable.

This value is a GUID which you can match with the a Regex like the one shown below.

pm.test("Body matches string", function () {
    var regEx = new RegExp('(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}');
    pm.collectionVariables.set("access_token", regEx.exec(pm.response.text())[0]);
    console.log(pm.collectionVariables.get("access_token"));
});

Found a solution

const response = pm.response.text();
//find a match with a regex
let authCode = response.match(/authorizationCode = '(.*?)';/g);
//remove first and last characters as needed with slice;
//console.log(authCode[0].slice(21, -2));

pm.collectionVariables.set("authorization_code", authCode[0].slice(21, -2));
Related